How to save images to a new folder matlab - 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.

Related

delete files with numbered names in matlab directory

I'm new to matlab and I've wrote a code that implements the gamma function for image processing. I generate around 300 photos named '001.jpg' to '300.jpg' and then use ffmpeg to make a video.
In the end, I only need the video result and need a command to delete all the photos generated in the directory! is there a way to do that?
If you want to remove all .jpg files in the current directory you can use the delete command with a wildcard (*)
delete('*.jpg')
If the files live in a folder other than the current directory, you can specify the directory in this way.
folder = '/path/to/my/files';
delete(fullfile(folder, '*.jpg'))
If you want to limit it to just files that have number filenames, you could do something like the following
files = dir('*.jpg');
filenames = regexp({files.name}, '^[0-9]+\.jpg$', 'match', 'once');
filenames = cellstr(cat(1, filenames{:}));
delete(filenames{:})
Adding to Suever's answer (not allowed to comment yet):
Assuming you already know the names of the images you're creating, you could save your script a 'trip' to the folder and back by creating the filenames list yourself thus:
for i=1:numOfImages
filenames(i)={strcat(num2str(i),'.jpg')};
end
delete(filenames{:})

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.

Open multiple subfolders within a loop

I have a folder named "Photos" that is a subfolder of the current directory. Inside that folder, there are four subfolders with names "Order1", "Order2",
"Order3", "Order4". I am trying to open these subfolders using a loop.
The following code is not working.
for i=1:4
current_path=pwd;
cd(current_path');
cd('Photos\Order%d',i);
end
There are a lot issues going on here at the same time.
The primary issue is that you are changing directories each time through the loop but you're also getting the value of the current directory (pwd) each time. The directory doesn't automatically reset to where you were when it goes back to the top of the loop. I think you expect current_path to be the folder you started in and be the same for all iterations.
You need to use sprintf or something similar to create your "OrderN" folder names. cd doesn't know what to do with the format specifier you're trying to use.
You should always use fullfile when concatenating file paths. Period.
You should use absolute paths when possible to remove the dependence upon the current directory.
Do you really need to change the working directory? If you're trying to load files within these folders, please consider using absolute file paths to the files themselves rather than changing folders.
If you are going to do this this way, please be sure to reset the path back to where it was at the end of the loop. There is nothing worse than running code and ending up in a directory that is different than where you were when you called it.
To actually make your code work, we could do something like this. But given all of my points above (specifically, 4-5), I would strongly consider a different approach.
startpath = pwd;
for k = 1:4
folder = fullfile(startpath, 'Photos', sprintf('Order%d', k));
cd(folder)
end
% Set the current directory to what it was before we started
cd(startpath)

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 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.