how do I define an index for the subplot position from two indexes of nested for loops?

22 views (last 30 days)
I have a nested for loop that looks like such:
for i=1:length(input1)
for j=1:length(input2)
[x,y]=function(input1(i),input2(j))
end
end
but for each iteration of the nested for loop I would like to plot x vs. y in a subplot of dimensions i by j
so I am trying to update my code to look something like:
for i=1:length(input1)
for j=1:length(input2)
[x,y]=function(input1(i),input2(j))
k = ??? I can't figure out how to define this index...
subplot(length(i),length(j),k)
end
end
what is the right way to define an index, k, so that as the nested for loop runs it will subplot x vs. y in the correct position of a i by j dimensional subplot that corresponds to the current values of i and j ??
any help is greatly appreciated!! :)

Accepted Answer

Guillaume
Guillaume on 23 Oct 2015
Use sub2ind:
subplot(numel(input1), numel(input2), sub2ind([numel(input1), numel(input2)]), i, j)
Note that it should be length(input1) instead of length(i), same for j. I prefer numel to length, it's safer.
Also, use better variable names than input1 and input2, like something that actually says what's in them.
  2 Comments
Daniel
Daniel on 23 Oct 2015
Great idea, exactly what I needed, and yes you are also right, I meant to put length(input1) and length(input2) for the subplot dimensions, Thanks for the help Guillaume! :)
Karl Neuhäuser
Karl Neuhäuser on 26 Oct 2021
There has to be a syntax error here, one bracket ) is at the wrong spot, isn't it?
subplot(numel(input1), numel(input2), sub2ind([numel(input1), numel(input2)], i, j))

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!