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

답변 (1개)

Robert U
Robert U 2020년 4월 21일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2020년 4월 20일

답변:

2020년 4월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by