2

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
5
  • First, it looks like you are using correlation function in the wrong way: it must contain 4 arguments (5th is not necessary). Look at this documentation. And the second: correlation cannot works for i and j of array type, so I think we can avoid loop using some arrayfun or bsxfun but we still have to use correlation for 16m times (4000*4000)... But I'm not sure here :) Commented Dec 9, 2016 at 7:12
  • thank you for your reply @Mikhail_Sam; but corrlation function is a function that written by me. I have edited my question. Commented Dec 9, 2016 at 7:23
  • Ah, okay! Than I advise you to rename it for avoiding overwriting built-in function name. To help you we need to see it's code: maybe we can vectorize some actions into it! Commented Dec 9, 2016 at 7:27
  • thank you for your advice @Mikhail_Sam; I corrected it; and I have added my corr function Commented Dec 9, 2016 at 7:47
  • I'm not joking but corr is built in function too: MATLAB doc :D Ok, now let's try to workaround for you function... Commented Dec 9, 2016 at 7:59

1 Answer 1

2

Here is a vectorized version:

C = cov(SelectedData);
V = sqrt(diag(C));
VP2 = bsxfun(@times,V,V.');
CORR = C ./ VP2;
Red1 = sum(abs(CORR(:)));
Sign up to request clarification or add additional context in comments.

1 Comment

Glad if it can help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.