Question

I want to export my data in two figures with four subplots each. But when I try to do this inside a loop it keeps printing only the second figure with four plots. And when I use figure, it prints eight figures with one plot each. Here is the part of code:

subplot(2,2,k);
plot(2.^[4:2:10], a, '-mo', 2.^[4:2:10], b, '-r+', 2.^[4:2:10], c, '-bx'  );
axis([2.^4, 2.^10, 0, max([max(a), max(b), max(c)])]);    
str = sprintf('Time for m1 = 2^%d',i);
title(str);
xlabel('n ')
ylabel('s') 

subplot(2,2,k);
plot(2.^[4:2:10],a1, '-mo', 2.^[4:2:10], b1, '-r+', 2.^[4:2:10], c1, '-bx'  );
axis([2.^4, 2.^10, 0, max([max(a1), max(b1), max(c1)])]);    
str = sprintf('Time for m1 = 2^%d',i);
title(str);
xlabel('n ')
ylabel('M') 
Was it helpful?

Solution

your loop needs to look somehow like this:

x = 1:2;
y = x;

f = 2;  %number of figures
c = 2;  %number of plots per column per figure
r = 2;  %number of plots per row per figure
n = repmat(cumsum(ones(1,r*c)),1,f);  %index for subplots
h = ceil( (1:f*r*c)/(r*c) ); %index of figures

for ii=1:f*r*c

   % calculations

   % plot specifier
   figure( h(ii) )
   subplot( r,c,n(ii) )

   % plot
   plot(x,y)

   % your plot properties
end

it gives you a figure(1) with 2x2 subplots and a figure(2) with 2x2 subplots

and for example

f = 3;  %number figures
c = 3;  %number of columns per figure
r = 4;  %number of rows per figure

would give you 3 figures with 3x4 plots each and so on...


If the order in which the plots appear matters, you can change the way h and n are created. These are just examples. Basically they are just vectors relating your index ii with the appearance order.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top