subplot automatically fill in next position for selection of plots in for loop

21 ビュー (過去 30 日間)
Kitt
Kitt 2025 年 11 月 26 日 20:50
コメント済み: dpb 2025 年 11 月 28 日 14:56
I have a state variable that ranges from 1:20 but I only want to plot 4:11 in a 2x4 grid.
I'm trying to use the subplot function, but I can't figure out how to make the plots show up in the position I want them to.
Essential what I have is
state = 4;
subplot(2,4,1)
for state = 5:11;
subplot(2,4,state)
end
but when I have the position for states 5:11 as "state" it offsets them as if those other states I'm not selecting were there, and I end up with this
is there a way to have the 5:11 plots just fill in the next position without having to write them out one at a time? I've tried [2:8] and that didn't work.

採用された回答

dpb
dpb 2025 年 11 月 26 日 21:22
編集済み: dpb 2025 年 11 月 26 日 21:46
The subplots are sequentially numbered from 1:N as given in the construction. To use yours just
...
for state = 5:11
subpltIdx=state-4;
subplot(2,4,subpltIdx)
...
% plot stuff goes here...
end
...
You might find the newer tiledlayout and nexttile helpful here ...
tiledlayout(2,4)
...
for state = 5:11
nexttile
...
% plot stuff goes here...
end
While neither requires it, I would strongly recommend you save the handles to the axes in a 2D array on creation -- then one can access whichever axis is needed directly to make any later changes needed.
  2 件のコメント
Kitt
Kitt 2025 年 11 月 26 日 21:37
Oh duh, that's where the nexttile would go, within the for loop!
I had tried tiledlayout but couldn't get it to work because I was putting the nexttile above for state = 5:11. Very silly now, realizing my mistake there.
dpb
dpb 2025 年 11 月 28 日 14:56
Just a comment on the indexing...when have something of this sort with the subplot() construct where need the second counter, the alternate way besides the difference is something like
...
subpltIdx=0; % initialize a second counter
for state = 5:11
subpltIdx=subpltIdx+1; % increment the counter
...
This can be very effective in many situations to decouple the other counter from the loop index but keep in synch...

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2025 年 11 月 26 日 21:21
subplot(2,4,state-4)

カテゴリ

Help Center および File ExchangeSubplots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by