Execute script but don't touch workspace in Matlab - matlab

Can I execute script, but make it doesn't touch any current workspace variables? I.e. turn script into function?
Also it would be good to have access this script's variables after run.
I tried
evalin('myworkspace', 'myscript')
but it failed.
I tried
evalin('caller', 'myscript')
but it changed variables.
Is it possible to accomplish?

The trivial way to accomplish this without changing the script itself would be to:
save
myscript
% ... examine variables
clear
load
save saves the current workspace to a MAT-file called "matlab.mat". You can give it a different name if you prefer. load loads it in again. If you specified a different name for save, give the same name to load.

If you have the parallel computing toolbox, you can do it by submitting the script to your local cluster. (Just to emphasise, your local cluster is your own pc.)
E.g. if you have a script SO.m with the line
a = randn;
then you can submit and wait using
job = batch('SO', 'Profile', 'local');
wait(job);
Once it have finished running, you can load the variables using
M = load(job);
then all the variables are fields of M.
>> M.a
ans =
0.4010

Related

Matfile isn't loading the structure's field names

Background
I encountered some strange behaviour with the function "matfile" in Matlab 2016b - not sure what's going on, and I can't replicate it or create a test case.
I have a structure, which I saved to a server, like so:
PathToFile='ServerPath\My Documents\MyProj\testMatF.mat';
save(PathToFile,'-struct','myStruct'); %I tried the -v7.3 flag
Problem
Then I read it in with:
m1=matfile(PathToFile);
On other, very similar structs, I can do:
myFields=fieldnames(m1);
But for this one file I can't, all I get is the auto "Properties" field.
What I've tried
myFields=who(m1) - gives me list of fieldnames... sometimes. I don't know the who function well, but it seems, if I intersperse who m1 then myFields=who(m1) it works.
Explicitly typing m1.TheFieldName, works.
Moving the file to a location on the comp, like C:\Data\. Then using fieldnames works.
Using load, works.
Does it have to do with the server access, corrupted file, matfile properties? One other weird thing is some of my .m files in this particular folder, when I try to open them results in: Does not exist, when clearly it does, since I click on it and can use the run function with it... Additional: Windows 7. Recently updated license.
Please let me know what info you can use to help out. Either to create a new file that will work, or fix the problem with the current file. Thanks.
EDIT
Example output in my command window - seemingly incomprehensible...
m1=matfile(fullfile(projPath,'NexusMarkersProcessed.mat'),'Writable',false)
m1 =
matlab.io.MatFile
Properties:
Properties.Source: '\bontempi.medicine.utorad.utoronto.ca\home\PT\zabjeklab3\My
Documents\Data\Active Projects\JC_Hip\FL1502\FL1502\Patient
Classification 2\NexusMarkersProcessed.mat'
Properties.Writable: false
Methods
K>> m1.Properties.Source
ans =
\bontempi.medicine.utorad.utoronto.ca\home\PT\zabjeklab3\My
Documents\Data\Active Projects\JC_Hip\FL1502\FL1502\Patient
Classification 2\NexusMarkersProcessed.mat
K>> java.io.File(m1.Properties.Source).exists()
ans =
logical
0
Pause to paste in this window... go back:
java.io.File(m1.Properties.Source).exists()
ans =
logical
1
K>> who(m1)
Your variables are:
Patient10 Patient5 Patient9 Patient11 Patient6 Patient3
Patient7
K>> who(m1) K>> who(m1) K>>
java.io.File(m1.Properties.Source).exists()
ans =
logical
0
K>>
So it sometimes finds the file, and can read it in. Othertimes it cannot - is this to do with the fact that it's on a network drive?
Any help is appreciated.
This issue is caused by accessing a file on a network drive. One workaround is to copy the file to a local drive (C: is used), and then use matfile, use the result as needed, then replace the network drive file, and delete the local file, to return things to their original state. Some research made me realize things are slower than they need to be if any files, even the .m ones, are on the network. Here's a function that worked:
function [m,noData]=safeMatFile(FilePath,safeFilePath)
%FilePath: absolute path to where the file is on the network
%safeFilePath: absolute path to where the file will be temporarily copied locally, C://
%safeDir='C:\Data';
%safeFold='tempFolder12345679';
%[~,tempDir,~]=mkdir(safeDir,safeFold);
%safeFilePath=fullfile(safeDir,safeFold,FileName);
noData=0;
dirFile=dir(FilePath);
if (length(dirFile) == 1) && ~(dirFile.isdir)%OR java below OR exist(forceFilePath,'file')==2
%if there is a file, make a temp folder on the C drive
if ~(java.io.File(safeFilePath).exists() && java.io.File(safeFilePath).isFile()) %ensure file doesn't exist, check dir too: || isempty(tempFolder)
copyfile(FilePath, safeFilePath);%moves existing file to backup folder
else
warning('SKIPPING (%s) - an old file of the same name was there, delete it!\n',safeFilePath);
return
end
%Load the temp local file into matlab
m=matfile(safeFilePath,'Writable',true);
else
m=[];
noData=1;
end
end
Then do stuff with m... and at the end:
function overwriteOldFiles()
if (java.io.File(safeFilePath).exists() && java.io.File(safeFilePath).isFile())
java.io.File(FilePath).delete();
java.io.File(safeFilePath).renameTo(java.io.File(FilePath));
end
end
and
function deleteTempFiles()
if (java.io.File(safeFilePath).exists() && java.io.File(safeFilePath).isFile())
java.io.File(safeFilePath).delete();
end
end
... Then rmdir if necessary.
Note, I tried different ways of checking if the file exists (I think the first is fastest and most reliable):
dirFile=dir(FilePath); if (length(dirFile) == 1) && ~(dirFile.isdir)
if (java.io.File(FilePath).exists() && java.io.File(FilePath).isFile())
if exist(FilePath,'file')==2

Is it possible to call a script from within another script in Octave?

PHP has the nifty include() function to bring in external files into the main script. Is this possible in Octave? I tried using load() but I keep getting an error: error: load: unable to determine the file format of 't_whse.m' which makes me think this is the wrong way to do this or that it's actually not possible in Octave.
You don't need to call load, as load is reserved for loading data from a file. Instead, you just want to call the script by name. This will (if it's actually a script) execute the script and make any variables that were defined in that script accessible to the calling script.
script1.m
disp('Beginning of script1');
script2;
fprintf('Value = %d\n', value)
disp('End of script1')
script2.m
disp('Beginning of script2');
value = 2;
disp('End of script 2');

MATLAB Automate GUI

I currently have a GUI that outputs a single text file based on various input parameters. However, I need to modify my application such that the GUI outputs multiple text files based on N inputs. The original GUI designer is no longer available and the main m-file has over 5k lines of code making it difficult to troubleshoot (not to mention the code is very unorganized and not commented). Does anyone have any suggestions on how I can run the GUI N times based on the N inputs and output N text files without modifying the original m-file?
Assume your gui is called myApp and your callback to s called myButton_Callback.
I also assumng that the tag of the uicontrol is 'myButton'.
Here is the caller script:
myApp_h = myApp();
myApp_handles = guidata(myApp_h);
myButton_h = myApp_handles.myButton;
MyApp('myButton_Callback', myButton_h, myApp_handles);
You can automate any gui control by this method.

relation between main GUI's and sub GUI's

I have two GUIs namesd masir and SetOut
SetOut GUI is a sub GUI for masir(pressing a button on masir will open SetOut)
To access the data of masir in SetOut I have these 2 lines of code:
masirGUIhandle = masir;
masirGUIdata = guidata(masirGUIhandle);
but running these 2 lines will run the opening function of masir as I work in SetOut(In opening function I have set some initial values for my variables and now I don't want those initial values ,I need changed values for my variables) so I dont want the OpeningFcn of masir GUI to be runned ,I just need to have access to masir data in SetOut
What can I do to fix the problem?
Can any one help me about this answer and explain me more?
I use this easy way for data sharing between GUIs
%In the end of OpeningFcn of Main GUI
setappdata(0,'HandleMainGUI',hObject);
%When you want to edit shared data you must get the handle
HandleMainGUI=getappdata(0,'HandleMainGUI');
%write a local variable called MyData to SharedData, any type of data
setappdata(HandleMainGUI,'SharedData',MyData);
%get SharedData and save it to a local variable called SomeDataShared
SomeDataShared=getappdata(HandleMainGUI,'SharedData');
Don't forget to clean up the data shared in the CloseReqFcn of you main GUI
HandleMainGUI=getappdata(0,'HandleMainGUI');
rmappdata(HandleMainGUI,'MySharedData') %do rmappdata for all data shared
Remember that your GUIs might try to getappdata that doesn't exist, you should first test if it does exist
if (isappdata(0,'HandleMainGUI') & isappdata(HandleMainGUI,'MySharedData'))
%get, set or rm appdata
else
%do something else, maybe loading default values into those variables
end
Tell me more aboute which line of code should be written in MainGUI and which line should be written in SubGUI?
And tell me what does the responser mean by CloseReqFcn?
Well let me summarize how I see the problem.
You want to read the data from SetOut with out creating it? That's not possible like this as the data will be created when the window is created.
A nice and systematic way around would be doing it object oriented (see Model-View Controller Pattern) You can more or less copy an example from my answer here (Example for Event - Observer)
But if you'd like to stick with your code I also have some ideas:
If you don't want the window to show you could set it invisible with set(theGUIhandle,'Visible','off')
While the window is not closed you can obtain the data with getappdata(theGUIhandle)
If you want the data after the window is closed you need to have a function that stores it outside the window.

Windbg: Creating log of function entry and exit

I wish to create log of function entry and exit for my code. I am using the following command in WinDbg-
Function name and the return value
bm <module_name>!* "kcL1;.echotime;gu;r eax;.echotime;gc;"
Now I wish to do this for all the modules of the function but I don't want to write the code again for each module. Is there some way to specify bm to read module names from a file which I create using "lm" and set breakpoint for each module or something even more simple.
Also, how can I specify bm to not print the output on the screen? I am using a log file.
Sometimes I don't see the time for call exit. What can be the reason for this? How can I correct it?
you can use !for_each_module
You will not see call exit time if another breakpoint is hit (in another thread, or if the funciton calls other functions that have breakpoints)