Search code examples
matlabplotsave-as

MATLAB Saving Figure Invalid Filename Error


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.

Solution

  • 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.