Search code examples
matlabnested-loops

How can I simplify a nested loop in Matlab?


I want to simplify my code, because it is very time consuming. In my problem, R is a bout 4000, so corr function should be call for more than 16000000 times. haw can I simplify this code?

for i=1:R

    for j=1:R

        Red1 = Red1 + abs(corr (SelectedData,i,j));

    end

end

edit: So, I should say that, corr function is written by me and it compute correlation between two features.

and this is my corr function:

function corr = corr (X, i, j)

    covariance = (cov((X(:,i)),(X(:,j))));

    corr = (covariance(1,2))/((sqrt(var(X(:,i)))) * (sqrt(var(X(:,j)))) );


end

Solution

  • Here is a vectorized version:

    C = cov(SelectedData);
    V = sqrt(diag(C));
    VP2 = bsxfun(@times,V,V.');
    CORR = C ./ VP2;
    Red1 = sum(abs(CORR(:)));