0
votes

I am writing a program to plot graphs in a loop and I want to save each graph that comes out as a .jpg file with a variation of the file name. Here is my code for saving the graphs:

filename = strcat('WI_Pollutants_', D(i,6), '_200706_O3');
saveas(gcf, filename, 'jpg'); 

The saved file should come out as the following with D(i,6) changing each iteration of the loop.

WI_Pollutants_003-0010_200706_O3.jpg

However, I'm running an error: (Maybe it has to due with saveas wanting a string only?)

Error using saveas (line 81)
Invalid filename.
2
Could you include exactly what D(i,6) is prior to this loop? And for that matter, filename?PearsonArtPhoto
D is the sorted cell matrix of the O3 data. So it's all the data for O3_sorted. i goes from 1 to 32 and is the 32 unique county-site codes (sites where O3 is measure). Therefore, D(i,6) is the 6th column of O3_sorted, pulling out only the rows where the county-site code is the same as whatever is in i at the time (such as '003-0010' for i = 1). filename is what I want to name the graph that comes out. For example, WI_Pollutants_003-0010_200706_O3.jpg. filename creates this name, changing the 003-0010 part for each new graph.SugaKookie

2 Answers

4
votes

saveas only accepts characters as the filename. But when filename was created, strcat made it a cell array. Therefore, the filename needs to be converted to a character array.

 filename = char(strcat('WI_Pollutants_', D(i,6), '_200706_O3'));
 saveas(gcf, filename, 'jpg'); 

This solves the problem.

0
votes

I think your D{i,6} is ending up wrapped up as an array, from this line:

D{i,6} = [num2str(D{i,6}) '-' num2str(D{i,7})];

To solve this, just removing the []'s

D{i,6} = num2str(D{i,6}) '-' num2str(D{i,7});

I think what happened is your D{i,6}=['someString'], and concatinating added in the []'s that werent' desired.

As a check, if something like this happens again, just fprintf(filename) right before use, and look at what comes out. I suspect you'll find the issue there. You can always remove the print statement later on.