Mfj
Mfj

Reputation: 77

How to save a figure in matlab with different names for each figure based on the input?

I want to save my figure based on the input. In my function I have inputs that is dates:

2016-08-02
2016-09-02 ect.

I want to save the output figure for each date and I want the name to contain the date. Ex:

 figure20160802.pdf
 figure20160902.pdf  ect.. 

Started with this code

saveas(figure, 'myfigure' yyyy mm dd, pdf) 

That is obviously wrong. Someone know what to do?

Upvotes: 1

Views: 329

Answers (2)

Tom
Tom

Reputation: 1125

You can use saveas(figure_handle, file_name) where file_name is a string which is the name of the file, including the date and the extension .pdf. You don't need a third argument to saveas.

If you want to save the current figure, just replace figure_handle with gcf()

So your question is really how to construct the file_name string. For example, if your date is in a string called the_date then you can use the [] concatenation operators for example:

the_date = '20160802';
file_name = ['myimage' the_date '.pdf'];
saveas(gcf(), file_name)

If your date string the_string contains hyphens and you don't want them in the filename, you'll have to do a little more work to remove the hyphens:

the_date = '2016-08-02';
the_date = strrep(the_date, '-', '');
file_name = ['myimage' the_date '.pdf'];
saveas(gcf(), file_name);

You may need to modify this depending on how you have the date stored, but you get the idea

Upvotes: 2

Murad Omar
Murad Omar

Reputation: 90

You can use imwrite(image, [file_name '.png']) alternatively if you want to save them as pdf you can use: print(h, file_name, '-dpdf') where h is the handle to you image.

Upvotes: -1

Related Questions