How to avoid using a loop here?

조회 수: 1 (최근 30일)
sznailc
sznailc 2021년 10월 19일
답변: Star Strider 2021년 10월 19일
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

채택된 답변

Star Strider
Star Strider 2021년 10월 19일
One approach —
N = 5;
tic
[m,n] = ndgrid(1:N);
A = 2*N + 1 - (m + n)
A = 5×5
9 8 7 6 5 8 7 6 5 4 7 6 5 4 3 6 5 4 3 2 5 4 3 2 1
toc
Elapsed time is 0.047132 seconds.
Compare —
tic
A = zeros(N);
for m = 1:N
for n = 1:N
A(m, n) = 2*N + 1 - (m + n);
end
end
toc
Elapsed time is 0.003632 seconds.
A
A = 5×5
9 8 7 6 5 8 7 6 5 4 7 6 5 4 3 6 5 4 3 2 5 4 3 2 1
The nested loops are actually faster!
.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by