for loop - Array indexing problem

4 visualizaciones (últimos 30 días)
Arnar Þór Ólafsson
Arnar Þór Ólafsson el 20 de Abr. de 2020
Respondida: Robert U el 21 de Abr. de 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

Respuestas (1)

Robert U
Robert U el 21 de Abr. de 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

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by