How to plot a tiled layout using a loop?

216 views (last 30 days)
Hi guys, I have bunch of excel files that almost everything in them is similar. All I want is creating a loop instead of coding 10 figures, that some data is loaded from row (I can get this part done), then using a tiled layout or subplot to click run and MATLAB loops and adds figures to the next tile but I cant get this going:
for r = 1:10
X=xlsread(B) - for instance
scatter(X(the plot works))

Accepted Answer

ANKUR KUMAR on 12 Mar 2021
Edited: ANKUR KUMAR on 12 Mar 2021
for r = 1:10
If you have two loops, you can use as follows:
for r = 1:2
for k=1:5
subplot(2,5,(r-1)*5+k) % 5 is used because the maximum iteration of k is 5
ANKUR KUMAR on 12 Mar 2021
We need to use cat command to concatenate multiple separate matrices into a single matrix. The first argument in the cat command is the dimension along which you wish to concatenate.

Sign in to comment.

More Answers (2)

Adam Danz
Adam Danz on 12 Mar 2021
Edited: Adam Danz on 12 Mar 2021
> should a nexttile be in the loop?
Yes, but the tiled layout should be defined before the loop.
The first two examples listed in this answer show how to use tiledlayout in a loop with a global legend.
Here's another example.
fig = figure();
tlo = tiledlayout(2,3);
h = gobjects(1,6);
colors = lines(6);
for i = 1:6
ax = nexttile(tlo);
h(i) = plot(ax, 1:10, rand(1,10), 'Color', colors(i,:), 'DisplayName', sprintf('line %d',i));
lg = legend(h);
lg.Layout.Tile = 'East'; % <-- place legend east of tiles
  1 Comment
Wolfgang McCormack
Wolfgang McCormack on 13 Mar 2021
@Adam Danz thank you so much Adam, you are a savior for me on this forum! I don't know what I had to do without you! thx

Sign in to comment.

Wolfgang McCormack
Wolfgang McCormack on 12 Mar 2021
Hey Adam, @Adam Danz
I saw your answer on this post:
Could you please teach me how to corporate that in a for loop? should a nexttile be in the loop?
Thank you!
Adam Danz
Adam Danz on 9 Mar 2022
Edited: Adam Danz on 9 Mar 2022
nFigures = 17; % number of figs
subplotGrid = [5,5]; % subplot grid arrangement
nAxes = prod(subplotGrid);
figHandles = gobjects(1,nFigures);
axesHandles = gobjects(nFigures, nAxes);
for i = 1:nFigures
figHandles(i) = figure();
for j = 1:nAxes
axesHandles(i,j) = subplot(subplotGrid(1),subplotGrid(2),j,figHandles(i));
Not tested

Sign in to comment.


Find more on Graphics Object Programming in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!