Asked by Mmotevasseli(alex)
on 6 Mar 2019

I wanna know how should i write a function to generate correlation matrix without using functions like corr,corrcoef,corr2, etc.

i tried different way but didn't work,.

for j=1:7

for k=1:7

mj = mean(X(:,j));

mk = mean(X(:,k));

s(j,k)=1/19 * sum((X(:,j)-mj).*(X(:,k)-mk));

end

end

for l=1:7

for m=1:7

ml=mean(X(:,l));

mm=mean(X(:,m));

standard_dev1=sqrt(1/19 * sum((X(:,l)-ml).^2));

standard_dev2=sqrt(1/19 * sum((X(:,m)-mm).^2));

correlate(l,m)=s(l,m)/standard_dev1*standard_dev2;

end

end

my dataset is a 20*7 matrix

main diameter of correlation must be 1.

I had trouble understanding the formula.

Answer by Jos (10584)
on 6 Mar 2019

Step 1 - Write a function that calculates the correlation between two vectors X and Y with equal lengths, using the formula you can find, e.g., here: https://www.dummies.com/education/math/statistics/how-to-calculate-a-correlation/

function C = MyCorrelationFunction(X,Y)

meanX = mean(X) ;

meanY = mean(Y) ;

sdX = std(X) ;

% etc, you can implement this yourself

C = ...

Step 2 - call this function for each pair of columns in your matrix M

for a=1:size(M,2)

for b = 1:size(M,2)

MyCorrelations(a,b) = MyCorrelationFunction(M(:,a),M(:,b)) ;

end

end

Mmotevasseli(alex)
on 7 Mar 2019

Assignment has more non-singleton rhs dimensions than non-singleton subscripts

Error in test3 (line 8)

correlate(i,j)=mycorrelation(x(:,i),x(:,j));

i get this error

Jos (10584)
on 7 Mar 2019

Does your function return a single value?

For instance, what does mycorrelation([1 2 3],[1 2 4]) return?

Jos (10584)
on 7 Mar 2019

a correlation between two vectors should be a single number.

There must be an error inside the function mycorrelation.m, I think.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Jos (10584) (view profile)

Direct link to this comment:https://it.mathworks.com/matlabcentral/answers/448663-work-with-a-data-set-to-compute-std#comment_678278

## Steven Lord (view profile)

Direct link to this comment:https://it.mathworks.com/matlabcentral/answers/448663-work-with-a-data-set-to-compute-std#comment_678281

Sign in to comment.