for loop - Array indexing problem
이전 댓글 표시
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
2020년 4월 21일
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.
- for loop
- array indexing
- ind2sub - convert linear indices to subscripts
- sub2ind - convert subscripts to linear indices
Kind regards,
Robert
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!