How to rewrite the nested for loop to modify matrix elments when matrix size is huge
4 views (last 30 days)
Show older comments
Hi I have the below matrix MN which is already pre-defined and I want to modify its elements without using for loop. Here I just set N=2 but in reality N is around 500. f(m) and g(n) are just user-defined functions. Is there a better way to rewrite it avoiding nested for loops?
N=2;
NN=N^2;
MN=sparse(NN*6,NN*6);
tic;
for m=1:N
for n=1:N
m_offset = (m-1)*N+n;
n_offset = (m-1)*N+n;
MN(m_offset,n_offset) = f(m);
MN(m_offset,n_offset+NN) = g(n);
end
end
toc;
0 Comments
Answers (1)
Matt J
on 14 Feb 2022
To vectorize this, you must vectorize f() and g().
Also, building a sparse matrix this way is a bad idea. You should use the syntax,
MM=sparse(I,J,S,NN*6,NN*6)
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!