Reputation: 997
Is there a way to create subplots dynamically in matlab ?
I have a variable X that determines the number of graphs to be plotted, i was wondering if there was a way to dynamically create these graphs since X will vary according to a certain scenario
I currently allocate the number of subplots beforehand like so:
figure
ax1 = subplot(3,1,1);
ax2 = subplot(3,1,2);
ax3 = subplot(3,1,3);
plot(ax1,ins,state_vec(:,1),'b',x,100,'r','LineWidth',2)
plot(ax2,ins,state_vec(:,2),'b',x,100,'r','LineWidth',2)
plot(ax3,ins,state_vec(:,3),'b',x,100,'r','LineWidth',2)
Upvotes: 1
Views: 2375
Reputation: 1325
If anyone is still asking this question, MATLAB since R2019b now recommends using the tiledlayout and nexttile function pair to dynamically arrange multiple plots inside one figure, e.g.
tiledlayout('flow')
nexttile
plot(x,y1)
nexttile
plot(x,y2)
Upvotes: 1
Reputation: 77
If you want it to be a square, you can do:
figure
sqSize = ceil(sqrt(X));
for i=1:X
subplot(sqSize,sqSize,i);
<plot stuff>
end
Upvotes: 0
Reputation: 1622
If you only want them in one column (just like you have them now), a simple for loop should do it:
figure
for i = 1:X
axi = subplot(X,1,i)
plot(axi,ins,state_vec(:,i),'b',x,100,'r','LineWidth',2)
end
If you want a grid, you'll have to be cleverer than that, but you can do it with two for loops. If you can, try R + ggplot2! :)
Upvotes: 1