MATLAB Answers

for loop - Array indexing problem

1 view (last 30 days)
Arnar Þór Ólafsson
Arnar Þór Ólafsson on 20 Apr 2020
Answered: Robert U on 21 Apr 2020
I'm working on a program, and one part of it can be seen below. I need the for loop to start at i = 1 and j = 2 only for the x variable but still run trough points like (i=2,j=1)(So obviously adding +1 to j doesn't work). Do you have any ideas how that is possible? Note, point (i=1,j=1) has to be valid for z and y. Thanks in advance!
for i = 1:10
for j = 1:12
if x(i,j) > y(i,j)
z(i,j) = y(i,j) - x(i,j)
else
z(i,j) = x(i,j) / x(1,1)
end
end
end

Answers (1)

Robert U
Robert U on 21 Apr 2020
Hi Arnar Þór Ólafsson,
you can use any vector to run for-loops. You can assign the values in the order as you wish. It might be necessary to preallocate the result matrix in order to avoid errors assigning elements that do not exist, yet.
Result = zeros(3);
indRow = [2 3 1];
indCol = [2 1 3];
ind = 1;
for ik = indRow
for jk = indCol
Result(ik,jk) = ind;
ind = ind + 1;
end
end
You can use index-pairs (row & column) or single index. You can even convert between these two index descriptions.
Kind regards,
Robert

Community Treasure Hunt

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

Start Hunting!