user13514
user13514

Reputation: 169

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?

Upvotes: 1

Views: 381

Answers (2)

NLindros
NLindros

Reputation: 1693

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

Upvotes: 1

Leos313
Leos313

Reputation: 5627

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

Upvotes: 0

Related Questions