simple Matrix manipulation without for-loop needed
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Marko
am 30 Dez. 2020
Bearbeitet: Bruno Luong
am 10 Jan. 2021
Hello Community,
i need your help.
I have a matrix which size is (N+1,N+1). I have also some vectors with different length. The elements of these vectors contain integer numbers.
The code above is modifying the matrix L in such a way, that it reads at first the first elemtn of vector vec and it set the row with the index = vec(i) to zero. and set a 1 on L(index,index).
This is accomblished by a slow for loop.
Do you have any ideas how it could be done in a more faster and elegent way?
function L = modifyLDirichlet(L,vec)
for i=1:numel(vec)
L(vec(i),:) = 0;
L(vec(i),vec(i)) = 1;
end
end
Thank you for your advice!
Best,
MJ
0 Kommentare
Akzeptierte Antwort
Bruno Luong
am 30 Dez. 2020
L(vec,:) = 0;
L(sub2ind(size(L),vec,vec)) = 1;
5 Kommentare
Bruno Luong
am 10 Jan. 2021
Bearbeitet: Bruno Luong
am 10 Jan. 2021
For sparse matrix you should avoid to set non-zero elements to 0 ad vice versa at the first place.
Never repeat sufficiently: Try to build sparse matrix is recommended using only once the command
S = sparse(I, J, S, ...)
if you look for efficiency.
But I find your comment a little off-topic, you never mention you have sparse matrix in your orginal question or when you make a comment "i have found a much faster solution" coming from no-where with no information to backup.
If you want to compare or improve speed with your specific need and matrix structure, please open another thread.
I'll stop comment on side topic.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Performance and Memory finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!