How do I write correlation coefficient manually in matlab?

1.4k Views Asked by At

The following is a function that takes two equal sized vectors X and Y, and is supposed to return a vector containing single correlation coefficients for image correspondence. The function is supposed to work similarly to the built in corr(X,Y) function in matlab if given two equal sized vectors. Right now my code is producing a vector containing multiple two-number vectors instead of a vector containing single numbers. How do I fix this?

function result = myCorr(X, Y)

meanX = mean(X);
meanY = mean(Y);
stdX = std(X);
stdY = std(Y);

for i = 1:1:length(X),
    X(i) = (X(i) - meanX)/stdX;
    Y(i) = (Y(i) - meanY)/stdY;
    mult = X(i) * Y(i);
end

result = sum(mult)/(length(X)-1);
end

Edit: To clarify I want myCorr(X,Y) above to produce the same output at matlab's corr(X,Y) when given equal sized vectors of image intensity values.

Edit 2: Now the format of the output vector is correct, however the values are off by a lot.

1

There are 1 best solutions below

1
Nirvedh Meshram On

I recommend you use r=corrcoef(X,Y) it will give you a normalized r value you are looking for in a 2x2 matrix and you can just return the r(2,1) entry as your answer. Doing this is equivalent to

r=(X-mean(X))*(Y-mean(Y))'/(sqrt(sum((X-mean(X)).^2))*sqrt(sum((Y-mean(Y)).^2)))

However, if you really want to do what you mentioned in the question you can also do

r=(X)*(Y)'/(sqrt(sum((X-mean(X)).^2))*sqrt(sum((Y-mean(Y)).^2)))