Home Vectorizing for loop on square matrix in matlab

# Vectorizing for loop on square matrix in matlab

oldflatop
1#
oldflatop Published in 2018-01-12 12:03:00Z
 I have a big square matrix (refConnect) with approx 500000 elements. I need to perform this operation: tmp = find(referenceCluster == 67); for j=1:length(tmp) refConnect(tmp(j),tmp)=1; end  I wonder if there is a simple way to vectorise this so I can avoid the for loop which is taking forever. Thanks for any help. Cheers
Andrei Davydov
2#
Andrei Davydov Reply to 2018-01-12 12:34:40Z
 Seems you can't significantly decrease execution time. Try evaluate the execution time with this test function. function test_spped(N, M) if nargin < 1 N = 707; end if nargin < 2 M = 2; end refConnectIn = rand(N, N); referenceCluster = randi(M, N, 1); refConnectA = refConnectIn; tic tmpA = find(referenceCluster == 1); for j=1:length(tmpA) refConnectA(tmpA(j),tmpA) = 1; end toc refConnectB = refConnectIn; tic tmpB = referenceCluster == 1; refConnectB(tmpB, tmpB) = 1; toc if isequal(refConnectA, refConnectB) disp('Result are equals'); else disp('Result are UNEQUALS!'); end  With default parameters you get: >> test_speed Elapsed time is 0.002865 seconds. Elapsed time is 0.001575 seconds. Result are equals  Note, the execution time of the vectorized code (B case) can be worse for large M: >> test_speed(707,1000) Elapsed time is 0.001623 seconds. Elapsed time is 0.002219 seconds. Result are equals 
 You need to login account before you can post.
Processed in 0.29637 second(s) , Gzip On .