MATLAB: How to define an index for the subplot position from two indexes of nested for loops

nested for loopsubplot position index

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!! 🙂

Best Answer

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.
Related Question