How to rewrite the nested for loop to modify matrix elments when matrix size is huge

1 Ansicht (letzte 30 Tage)
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;

Antworten (1)

Matt J
Matt J am 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)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by