oldflatop
oldflatop

Reputation: 39

Vectorizing for loop on square matrix in matlab

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

Upvotes: 0

Views: 77

Answers (1)

Andrei Davydov
Andrei Davydov

Reputation: 315

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

Upvotes: 0

Related Questions