InfiniteVariance
InfiniteVariance

Reputation: 81

matlab code nested loop performance improvement

I would be very interested to receive suggestions on how to improve performance of the following nested for loop:

I = (U > q); % matrix of indicator variables, I(i,j) is 1 if U(i,j) > q

for i = 2:K

    for j = 1:(i-1)

        mTau(i,j) = sum(I(:,i) .* I(:,j));

        mTau(j,i) = mTau(i,j);

    end

end

The code evaluates if for pairs of variables both variables are below a certain threshold, thereby filling a matrix. I appreciate your help!

Upvotes: 1

Views: 57

Answers (2)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

You can use matrix multiplication:

I = double(U>q);
mTau = I.'*I;

This will have none-zero values on diagonal so you can set them to zero by

mTau = mTau - diag(diag(mTau));

Upvotes: 3

Divakar
Divakar

Reputation: 221574

One approach with bsxfun -

out = squeeze(sum(bsxfun(@and,I,permute(I,[1 3 2])),1));
out(1:size(out,1)+1:end)=0;

Upvotes: 0

Related Questions