0

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.
tshepang
  • 12,111
  • 21
  • 91
  • 136
SugaKookie
  • 780
  • 2
  • 17
  • 41
  • Could you include exactly what `D(i,6)` is prior to this loop? And for that matter, filename? – PearsonArtPhoto Nov 22 '13 at 19:10
  • `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 Nov 22 '13 at 19:15

2 Answers2

5

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.

SugaKookie
  • 780
  • 2
  • 17
  • 41
0

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.

PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142
  • I can't just get rid of the brackets. That makes the statement an open ended sentence and runs an error. But I tried the fprintf(filename) and it led to suggestions and errors that helped me figure out what was wrong. I just had to convert filename to a character instead of a cell in the line where I create it. Thanks. – SugaKookie Nov 22 '13 at 19:39