for loop options in Matlab
조회 수: 1 (최근 30일)
이전 댓글 표시
I just learned about Matlab's ability to use matrices as arguments to a for loop;
This displays the columns of the matrix A
A = magic(5)
for n = A
disp(n)
end
I was wondering if it is possible to obtain a sequential index into a loop like this. ie. if I want to print the column number along with the column itself, can I continue with the form above or would I need to revert to a more typical form like
A = magic(5)
for jj = 1:length(A)
disp(['Column #',num2str(jj)])
disp(A(:,jj))
end
댓글 수: 0
채택된 답변
Walter Roberson
2012년 9월 24일
You would need the more traditional form. There is no way to query which iteration number you are on.
댓글 수: 0
추가 답변 (2개)
Matt Fig
2012년 9월 24일
A = magic(5)
cnt = 1;
for jj = A
disp(['Column #' num2str(cnt)])
disp(jj),
cnt = cnt+1;
end
댓글 수: 4
Walter Roberson
2012년 9월 24일
Oh... yes, you are right, I had forgotten that it went by columns when matrices are used. blush
Shadow
2024년 4월 2일
enumer = @(my_array) cell2mat(arrayfun(@(x,idx) struct("cargo",x,"idx",idx), my_array(:).', 1:numel(my_array(:).'),UniformOutput=false));
data = rand(5,4)
s=size(data);
for elem = enumer(data)
[row,col] = ind2sub(s,elem.idx);
disp("Element " + string(elem.cargo) + " with index " + string(elem.idx) + " at location " + string(row) + "," + string(col))
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!