Save workspace of unknown workspace in Matlab - matlab

Is it possible to save workspace variables from a function that I am calling and cannot explicitly edit without file I/O?
I know I can use the save function to save all of the variable names in a workspace, but what if I wanted to save the workspace variables from a function that I am calling, like a built in function (mean, sum, etc).
I would like to save all of the variables from a function's workspace before it returns back to the function I am writing, and I would like to do it without opening the file each time and adding an extra line of code; is this possible?

In case anyone is interested:
I have yet to find a solution to the exact question I asked, but I found a solution that works well enough with a little extra file tracking.
Using the function onCleanup, you can specify that all the variables be saved right before the function returns to the caller. Using this and a little file parsing, you can open the code in question as a simple text file, and insert the onCleanup code anywhere in the file (easier than inserting save as the last line). Then, you can run the code and track the new .mat file using the previous file name or any naming method you choose.
That will enable you to save all the variables in a workspace just before the function exits, but it does require file parsing, see simple example below:
readFile = fopen('filename.m');
writeFile = fopen(['filename_new.m']);
%Ignore the first line (hopefully the function header, may need extra parsing if not)
functionHeader = fgets(readFile);
%Print the function header
fprintf(writeFile,functionHeader);
%Print the clean-up code
%NOTE: This can go anywhere in the file
fprintf(writeFile,sprintf('onCleanup(#()save(''%s.mat''))\n',filename)));
nextLine = fgets(readFile);
while ischar(nextLine)
fprintf(writeFile,nextLine);
nextLine = fgets(readFile);
end
With the above, a new file is created (filename_new.m) which needs to be run, and will create a mat file (filename.mat) with all of the workspace variables in it.
eval(newFileName(1:end-2));
Now, by tracking the .mat file, you can do whatever is necessary after this point. For my purposes, I was interested in the memory used by the said function, which is available by accessing the mat object of the .mat file.
matObj = matfile('filename.mat');
stats = whos(matObj);
fileSize = sum([stats.bytes]);

Try the "save" function.
Add this line in your called function:
save('filename')
Here is my sample code:
a=10; b=6;
c=addition(a,b);
And the function is defined as:
function [out]=addition(a,b)
out=a+b;
temp1=a;
temp2=b;
temp3=a-b;
save('C:\data.mat');
end

Related

Matlab: track all file handles that were opened/touched by script

I want to find all dependencies of my script (and/or all subfunctions/subscripts), but not only functions that are called but also external files that are loaded or touched (fopen). matlab.codetools.requiredFilesAndProducts (documentation here) doesn't capture the touched filenames, my next idea, shadow the fopen function using something like below (to copy the filename to a log file), resulted in an unexpected recursive loop.
failed because of (unexpected) recursive loop, where somehow the 'builtin' fopen is not called, rather this function itself:
function varargout=fopen(varargin)
%write opened filename to log file somewhere
varargout=builtin('fopen',varargin{:}); %attempt to call built-in fopen() as usual
end
I also checked Mathworks depencey reports etc, to no use. Any ideas? Thank you.

Variable output to workspace with correct function call in command window-fixed- [duplicate]

How can I create a function with MATLAB so I can call it any where in my code?
I'm new to MATLAB so I will write a PHP example of the code I want to write in MATLAB!
Function newmatlab(n){
n=n+1;
return n;
}
array=array('1','2','3','4');
foreach($array as $x){
$result[]=newmatlab($x);
}
print_f($result);
So in nutshell, I need to loop an array and apply a function to each item in this array.
Can some one show me the above function written in MATLAB so I can understand better?
Note: I need this because I wrote a code that analyzes a video file and then plots data on a graph. I then and save this graph into Excel and jpg. My problem is that I have more than 200 video to analyze, so I need to automate this code to loop inside folders and analyze each *.avi file inside and etc.
As others have said, the documentation covers this pretty thoroughly, but perhaps we can help you understand.
There are a handful of ways that you can define functions in Matlab, but probably the most useful for you to get started is to define one in an m-file. I'll use your example code. You can do this by creating a file called newmatlab.m in your project's directory that looks something like this
% newmatlab.m
function result = newmatlab(array)
result = array + 1
Note that the function has the same name as the file and that there is no explicit return statement - it figures that out by what you've named the output parameter(s) (result in this case).
Then, in the same directory, you can create a script (or another function) that calls your newmatlab function by that name:
% main.m (or whatever)
a = [1 2 3 4];
b = newmatlab(a)
That's it! This is a simplified explanation, but hopefully enough to get you started and then the documentation can help more.
PS: There's no "include" in Matlab; any functions that are defined in m-files in the current path are visible. You can find out what's in the path by using the path command. Roughly, it's going to consist of
Matlab's own directory
The MATLAB subdirectory of your Documents directory
The current working directory

saving data from workspace to different dirrectory in matlab

I have a loop which my main script run through that. I wounder to save some of my variables in different directory every time that my loop is running. I have used following script but its not working:
for i=1:size(whisk, 1);
my codes is here and it creates variables in my workspace like [format, measurements].
the rest is what I wote to save this variables:
mkdir('C:\videos\results\', num2str(i));
dumvar=0; % As matlab has problem with data>2GB, then I use this 2 line code for saving
save('measurenments','dumvar','-v7.3');
save(fullfile('C:\videos\results\', num2str(i),'measurenments'));
clear all;
close all;
end
but Unfortunately its not work!!!!!!!!!!!
Any help would be appreciated.
Sam
Except that measurenments is wrongly spelled (correct spelling is measurements), there is not so strange that it does not work. The first call to save, saves the variable dumvar in the current folder, with the format v7.3. The second call to save, saves the whole workspace as a file fullfile('C:\videos\results\', num2str(i),'measurenments'). Try this,
save(fullfile('C:\videos\results\', num2str(i),'measurenments'),'dumvar','-v7.3');
However it seems as the folder fullfile('C:\videos\results\', num2str(i),'measurenments') does not exist since you only create the folder mkdir('C:\videos\results\', num2str(i))
. Then matlab cannot save anything there. Try either to save as fullfile('C:\videos\results\', [num2str(i),'measurenments']) or create the directory mkdir('C:\videos\results\', [num2str(i),'\','measurenments']);
`

Save or Load Data from/to GUIDE/Workspace

I'm new in GUIDE in MATLAB. I have two different problems:
I would like to save in a .mat file all variables (about 1000) from workspace using a button in GUI in MATLAB. How can I do?
I have a button where after press on it I'm able to load a specific .mat file from my path, always using GUI, but I would like that the variables contained in this file, became presents in the base workspace.
In other words, I have a button, "LOAD", in GUIDE in MATLAB where I can load a .mat file, and the variables contained in the .mat file must be loaded into the 'base' workspace when the button is clicked.
Please help me.
For your first question, I would suggest just putting a command like save('filename.mat'); in the "Save" button's callback. But what variables? If they are in the base workspace, see my answer to your second question below.
To load data into the base workspace, you might try the evalin command:
evalin('base','load(''filename.mat'')');
The 'base' argument tells it to run the command in the base workspace.
If your file name is in a variable:
fname = 'filename.mat';
evalin('base',['load(''' fname ''')']);
Alternatively, you could use sprintf:
loadCmd = sprintf('load(''%s'')',fname);
evalin('base',loadCmd);

Save filename.m deleted my origonal filename.m file and replaced it with a new file. How to get the old back?

I tried to save my file using the command window in Matlab. Unfortunately it replaced my file with a new file. And now I am unable to get it back.
It's probably easy, but I am new to using the command window in Matlab.
You are out of luck on this one. Saving to a file will irretrievably overwrite any existing file with that name unless you specify otherwise with the -append option. In the future, if you have a data set that is important because it is either not reproducable or because it takes a long time to generate it, I would recommend either backing it up or saving it with a timestamp. This is one example:
function save_t(name,varargin)
save(sprintf('%s-%d',name,time),clock*[1e8 1e6 1e4 1e2 1 0].',varargin{:});
end
Save this to a file in you matlab path named "save_t.m" and then you can simply call it just like you would call the save function, but now it will add on a timestamp.
save_t filename
This will help to ensure that you don't accidentally overwrite an existing file.