saving data from workspace to different dirrectory in matlab - 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']);
`

Related

How to save a session on Matlab

I was trying to save my Matlab variables and environment into a session so that next time I can directly load them without repeating the codes. I know how to save the Workspace variables but their way of saving a session doesn't work. It's said to be File -> Save to a session. But I couldn't find the button "File".
Any thoughts?
OK Actually I figured out an alternative solution. I realized that I could save all the Workspace variables. But my variables are too huge. So I ended up saving all my commands in a .m script file.
So next time when I want to resume my work, I just type the name of that script file to run all the useful commands to create the working variables and set up the script paths I need.

Find location of current script (mlx-file) in MATLAB

I'm working on my MATLAB code in a number of different locations, and it would be really helpful if I could make the code aware of its location on the computer. Till now I worked with .m-files. For .m-files I found the following solutions:
%example 1
cd(fileparts(mfilename('fullpath')))
or
%example 2
tmp = matlab.desktop.editor.getActive;
cd(fileparts(tmp.Filename));
or
%example 3
S = dbstack('-completenames');
S(1).file
or
%example 4
which(mfilename)
But with MATLAB 2016a there comes a new feature called live script. And with that those solutions are not working anymore.
%For example I would like to do something like this
cd(MLX_FILELOCATION);
%or
which(mlxfilename)
(Edit III: Problem: I am not able to get the path/filelocation or name of the current opened/executed MATLAB-file. With *.m-files this is possible with the examples above. With *.mlx-files it is not possible anymore. And I prefere to use *.mlx-files instead of *.m-files.)
Outputs of the examples above executed in a *.mlx-file:
%example1: mfilename returns the path to the 'MatlabEvaluationHelper' in the 'AppData\Local\Temp'-folder
%example2: output is an empty array
%example3: same output as example1
%example4: same output as example1, because mfilename returns "MatlabEvaluationHelper"
Edit I:
My first goal is that I would like to change the "current folder" (-> "cd") to the path of the running script.
Why: In the same folder with the mlx-file I have for example .csv-files with data. And for example by tomorrow I have new folder. I copy the mlx_file and now I want to make sure that I don't use the csv-files from yesterday (because the current folder from yesterday is shown in the file browser of MATLAB) -> so I would like to change the "current folder" automatically with just copying the mlx-file into a new folder.
If there is a better practise for that, please let me know.
Thanks for helping
Edit II:
Example for a used workflow:
I programmed a MATLAB script. Saved it in folder "Dataset_ONE". Furthermure I copy "Dataset_ONE.csv"-file into the same folder. E.g. I now create a plot and save it as the "*.png" in folder "Dataset_ONE".
The day after I might have a second (a new and with that different) dataset "Datasset_TWO". I create a new folder "Dataset_TWO". Copy the MATLAB-files to the new folder. Open the MATLAB file there. Then, because of the default settings, MATLAB has changed the "Current Folder" to the new folder where I opened MATLAB.
But if I now open the MATLAB script in the first folder again (at the same time with the other dataset MATLAB script) I have to be careful about the current folder.
In this case it might be useful to have the described solution.
If what you want is some sort of way of preventing you running the wrong script on the wrong data without realising, then you could add a safety instruction at the top of each script, throwing an error if your current directory is not the same as the location of the script you're running. e.g.
>> assert (strcmp (pwd, '/absolute/path/to/my/script'));
As for loading the right data / saving to the right location, just load and save using absolute paths and there should be no confusion.

How to save images to a new folder matlab

I need help with saving images to a new folder in matlab.
for example take the following code
timesteps=1000;
for iii=1:timesteps
...
...
image(somegraph);
...
if mod(iii,10)==1
print(sprintf('%s_%d','Graph at time',iii),'-dpng')
end
end
this loop excutes some code which produces a graph and the graph updates with every itteration, i print out and save every 10th itteration,
is there a way to save all these iterations into a new folder, and so that if I run the same code again, the folder is not overwritten but a new folder is written?
Thanks
How about creating a folder according to the current date/time and storing the files there. So do something like
foldername=datestr(now,'yyyy-mm-dd HH-MM-SS');
mkdir(foldername);
cd(foldername);
% code to save the data here
% ...
BTW, don't use colons for the timestamp in your foldername as some OSes don't like it as file/directory names.

Save workspace of unknown workspace in 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

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.