How to avoid using a loop here?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello. I want to do the same thing without a loop.
A = zeros(N);
for m = 1:N
for n = 1:N
A(m, n) = 2*N + 1 - (m + n);
end
end
댓글 수: 0
채택된 답변
Star Strider
2021년 10월 19일
One approach —
N = 5;
tic
[m,n] = ndgrid(1:N);
A = 2*N + 1 - (m + n)
toc
Compare —
tic
A = zeros(N);
for m = 1:N
for n = 1:N
A(m, n) = 2*N + 1 - (m + n);
end
end
toc
A
The nested loops are actually faster!
.
댓글 수: 0
추가 답변 (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!