How to avoid using a loop here?
2 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Star Strider
on 19 Oct 2021
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 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!