0

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.

Teej
  • 179
  • 2
  • 2
  • 12
  • Possible syntax error. `zx` and `zy` would be singular values in your loop. I'm assuming you would want those as vectors? `zx(i)` and `zy(i)`? You can avoid looping by just computing what you want vectorized: `zx = (X - meanX) / stdX; zy = (Y - meanY) / stdY;`. Also, depending on your MATLAB version, you may need to explicitly perform element-wise multiplication: `mult = zx .* zy;`. – rayryeng Apr 19 '17 at 18:46
  • I have updated my function some but i still don't think it is returning the correct coefficient – Teej Apr 19 '17 at 19:39
  • Your `mult` is also incorrect. It's only reporting one value, which is at the end of the loop. – rayryeng Apr 19 '17 at 19:57
  • how would i change mult so that it stores the array of all of the values of the multiplied pairs of numbers? – Teej Apr 19 '17 at 20:01
  • Got it. I just needed to initialize mult before the loop and then index it and now everything works perfectly. – Teej Apr 19 '17 at 20:07
  • Yup that's right. I'm not sure if you want to write an answer or if you'll allow me to. – rayryeng Apr 19 '17 at 20:11

1 Answers1

2

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)))
Nirvedh Meshram
  • 419
  • 6
  • 13
  • it seems as if these functions are outputting matrices with way more values than the corr function does. – Teej Apr 19 '17 at 18:38