Search code examples
matlabgraphmatlab-figure

How to use print command with loops in Matlab


I have looked up this simple question regarding printing graphs in Matlab without success so far. I have a for loop of this type:

N = 5;
for sim = 1:10
  X = randn(sim,N);
  X = mean(X);

  figure;
  plot(X);
  print -depsc X;
end

I would like to print and save one new graph for each simulation, and automatically name it, for example, X1 for sim = 1, X2 for sim = 2, X3 for sim = 3, etc. How do I do this?


Solution

  • Try this:

    N = 5;
    for sim = 1:10
      X = randn(sim,N);
      X = mean(X);
    
      hFig = figure;
      plot(X);
    
      % create filename and print to eps
      filename = strcat('X',num2str(sim));
      print(hFig,filename,'-depsc');
    end
    

    Hope this helps!