MATLAB - printing graph with different output names - matlab

I have a MATLAB program that graphs some things and then outputs the graph to a file. If I run this program several times in the same directory, the file gets overwritten each time. How can I make it so the filename it outputs to changes...
I currently have this:
print -depsc myfigure
I have strings, rate and name, that I want to use, but can't get anything to work. If I can't use my strings, something random would be fine as well. Any way to do this?
Many thanks!

Name it with the current date and time:
print('-depsc2', ['prefix_' datestr(now, 30)])
run right now in PST, this creates a file called prefix_20100220T200733.eps. You can obviously change the prefix and/or the date format.

You can add current time to your file name. For example:
m=magic(10);
fh=figure, surf(m);
currenttime= datestr(now,'MMSSFFF');
print(['-f',num2str(fh)],'-depsc',['outputFileName_',currenttime,'.eps']);

This code checks if file exists, and if yes, adds a counter to its name.
filename = 'myfigure';
if exist([filename '.eps'],'file')
k=1;
while exist([filename '_' num2str(k) '.eps'], 'file')
k=k+1;
end
filename = [filename '_' num2str(k)]);
end
print('-depsc', filename);

Its simple. worked for me.
currenttime= datestr(now,'dd-mm-yy_HH:MM')
filename= ['graph' currenttime '.jpg']
print('-dpdf',filename)
Or any other file format you want to export. check print help.

Related

Matlab saving a .mat file with a variable name

I am creating a matlab application that is analyzing data on a daily basis.
The data is read in from an csv file using xlsread()
[num, weather, raw]=xlsread('weather.xlsx');
% weather.xlsx is a spreadsheet that holds a list of other files (csv) i
% want to process
for i = 1:length(weather)
fn = [char(weather(i)) '.csv'];
% now read in the weather file, get data from the local weather files
fnOpen = xlsread(fn);
% now process the file to save out the .mat file with the location name
% for example, one file is dallasTX, so I would like that file to be
% saved as dallasTx.mat
% the next is denverCO, and so denverCO.mat, and so on.
% but if I try...
fnSave=[char(weather(i)) '.mat'] ;
save(fnSave, fnOpen) % this doesn't work
% I will be doing quite a bit of processing of the data in another
% application that will open each individual .mat file
end
++++++++++++++
Sorry about not providing the full information.
The error I get when I do the above is:
Error using save
Argument must contain a string.
And Xiangru and Wolfie, the save(fnSave, 'fnOpen') works as you suggested it would. Now I have a dallasTX.mat file, and the variable name inside is fnOpen. I can work with this now.
Thanks for the quick response.
It would be helpful if you provide the error message when it doesn't work.
For this case, I think the problem is the syntax for save. You will need to do:
save(fnSave, 'fnOpen'); % note the quotes
Also, you may use weather{i} instead of char(weather(i)).
From the documentation, when using the command
save(filename, variables)
variables should be as described:
Names of variables to save, specified as one or more character vectors or strings. When using the command form of save, you do not need to enclose the input in single or double quotes. variables can be in one of the following forms.
This means you should use
save(fnSave, 'fnOpen');
Since you want to also use a file name stored in a variable, command syntax isn't ideal as you'd have to use eval. In this case the alternative option would be
eval(['save ', fnSave, ' fnOpen']);
If you had a fixed file name (for future reference), this would be simpler
save C:/User/Docs/MyFile.mat fnOpen

MATLAB: Save figure with default name

I am running a matlab-script that produces a figure. To save this figure I use:
print(h_f,'-dpng','-r600','filename.png')
What this means is that if I don't change filename for each time I run the script, the figure filename.png will be overwritten.
Is there a way to save a figure to a default name, e.g. untitled.png, and then when the script is run twice it will make a new figure untitled(1).png instead of overwriting the original one?
You could create a new filename based on the number of existing files
defaultName = 'untitled';
fileName = sprintf('%s_%d.png', defaultName, ...
length(dir([defaultName '_*.png'])));
print(h_f,'-dpng','-r600', fileName)
Add a folder path to your dir search path if the files aren't located in your current working directory.
This will create a 0-index file name list
untitled_0.png
untitled_1.png
untitled_2.png
untitled_3.png
...
You could also use tempname to generate a long random name for each iteration. Unique for most cases, see section Limitations.
print(h_f,'-dpng','-r600', [tempname(pwd) '.png'])
The input argument (pwd in the example) is needed if you do not want to save the files in your TEMPDIR
You can try something like this:
for jj=1:N
name_image=sscanf('filename','%s') ;
ext=sscanf('.png','%s') ;
%%do your stuff
filename=strcat(name_image,num2str(jj),ext);
print(h_f,'-dpng','-r600',filename)
end
If you want to execute your script multiple time (because you don't want to use a "for") just declare a variable (for example jjthat will be incremented at the end of the script:
jj=jj+1;
Be careful to don't delete this variable and, when you start again your script, you will use the next value of jj to compose the name of the new image.
This is just an idea

Matlab publish - Want to use a custom file name to publish several pdf files

I have several data log files (here: 34) for those I have to calculate some certain values. I wrote a seperate function to publish the results of the calculation in a pdf file. But I only can publish one file after another, so it takes a while to publish all 34 files.
Now I want to automize that with a loop - importing the data, calculate the values and publish the results for every log file in a new pdf file. I want 34 pdf files for every log file at the end.
My problem is, that I couldn't find a way to rename the pdf files during publishing. The pdf file is always named after the script which is calculating the values. Obviously the pdf is overwritten within a loop. So at the end everything is calculated, but I only have the pdf from the last calculated log file.
There was this hacky solution to change the Matlab publish script, but since I don't have admin rights I can't use that:
"This is really hacky, but I would modify publish to accept a new option prefix. Replace line 93
[scriptDir,prefix] = fileparts(fullPathToScript);
with
if ~isfield(options, 'prefix')
[scriptDir,prefix] = fileparts(fullPathToScript);
else
[scriptDir,~] = fileparts(fullPathToScript);
prefix = options.prefix; end
Now you can set options.prefix to whatever filename you want. If you want to be really hardcore, make the appropriate modifications to supplyDefaultOptions and checkOptionFields as well."
Any suggestions?
Thanks in advance,
Martin
Here's one idea using movefile to rename the resultant published PDF on each iteration:
for i = 1:34
file = publish(files(i)); % Replace with your own command(s)
[pathStr,fileName,ext] = fileparts(file);
newFile = [pathStr filesep() fileName '_' int2str(i) ext]; % Example: append _# to each
[success,msg,msgid] = movefile(file,newFile);
if ~success
error(msgid,msg);
end
end
Also used are fileparts and filesep. See this question for other ways to rename and move files.

Saving Multiple Arrays to Text File in Matlab

I need to save multiple arrays to a text file with the filename the same as the variable name. I have created a vector of all the variables required using the follow lines.
all_var={};
vars=whos;
for(i=1:size(vars,1))
if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
all_var{end+1}=vars(i).name;
end
end
I am now struggling to find a way to save all of these variable to file. Any help would be appreciated.
Thank you
I'm not sure if I understood correctly. Do you want to save each variable in different files? Assuming you want to save all variables in the same file with, lets say, the first value of the vector as the filename, you could try something like:
filename = sprintf('vector_starting_with%d.mat', vars(1).name);
save(filename)
In case you want separated files for each element in the vector, you could try:
all_var={};
vars=whos;
for(i=1:size(vars,1))
if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
all_var{end+1}=vars(i).name;
varsave=sprintf('vector_%d.mat', vars(i).name)
save(varsave);
end
end
Sorry that it might have some bugs, right now I don't have MATLAB. Nevertheless, try to go over this documentation.
Edit Let me know if you try this then:
all_var={};
vars=whos;
for(i=1:size(vars,1))
if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
all_var{end+1}=vars(i).name;
filename = sprintf('%d.txt', vars(i).name);
file = fopen(filename,'w');
fprintf(file,vars(i).name);
fclose(file);
end
end

Why do I get a 0x1 cell? Matlab what function

I'm using the following code to look through all files in a particular directory, and I'm getting some strange results. The point of the program is to do the following: I'm looking through a huge number (~7000+) of .mat files for each day between 6-20-2007 and 9-20-2007. What I'm looking to do is search through each of these folders and look at the .mat files, etc. However, for some reason I'm getting a 0x1 cell that doesn't make sense to me. Maybe someone with a better trained eye can see why?
jDate = strtok( dates(j).name, '.' ); % Or dates(j,1).name
tradeFolder = sprintf( 'TAQ Data\\trades unzipped\\%s.tar\\%s\\', jDate );
tradeFiles = what(tradeFolder);
tradeMat = tradeFiles.mat;
quoteFolder = sprintf( 'TAQ Data\\quotes unzipped\\%s.tar\\%s\\', jDate );
quoteFiles = what(quoteFolder);
quoteMat = quoteFiles.mat;
(I have excluded the beginnings of the file paths since it includes my name). Anyways, how the data is saved is this: I extracted each day's worth of data and saved it to the folders listed above. Inside trades unzipped, for instance, will be a folder 20070620.tar, and inside that folder will be another folder named 20070620, and inside that folder is over 7000 .mat files. So....how come I'm getting a 0x1 cell for the tradeFiles.mat?
If anyone can help I'd greatly appreciate it.
A few comments
Both sprintf lines you have (tradeFolder=... and quoteFolder=...) has two '%s' in the formatted string, while only one argument: jDate. This might cause undefined behavior.
It is better to use fullfile to concatenate paths and file names.
Although using what in this context is correct, you might want to double-check it using dir( fullfile( tradeFolder, '*.mat' ) );
It is best not to use i and j as variables in Matlab.