Problem with matrices operations

2 views (last 30 days)
My Matlab knowledge is minimal and I was hoping someone could help me. I have generated two 4x900 size matrices. The matrices are X and Y. The operation that I must carry out is the following:
N=900
R(1)=(X(1st column)-Y(1st column))*transpose(X(1st column)-Y(1st column))
R(2)=(X(2nd column)-Y(2nd column))*transpose(X(2nd column)-Y(2nd column))
% ...
R(N)=(X(Nth column)-Y(Nth column))*transpose(X(Nth column)-Y(Nth column))
R_total=sum(R(1)+R(2)+...+R(N))
As an example, it would be something like this:
N=5;
X = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5];
Y = [5 6 7 8 9; 5 6 7 8 9; 5 6 7 8 9; 5 6 7 8 9];
R(1)=([1;1;1;1]-[5;5;5;5])*transpose([1;1;1;1]-[5;5;5;5]);
R(2)=([2;2;2;2]-[6;6;6;6])*transpose([2;2;2;2]-[6;6;6;6]);
% ...
R(5)=([5;5;5;5]-[9;9;9;9])*transpose([5;5;5;5]-[9;9;9;9])
R_total=sum(R(1)+R(2)+...+R(N));
The matrices R(1), R(2), ..., R(N) y R_total must have a size of 4x4.
I have been trying to use a 'while', but I don't know how to perform the operation. Does anyone know how I could solve it? I know I have comitted some errors calling R(1), R(2)...R(N).
Sorry if the process is not clear. I have tried to explain the operations as well as I could. If someone needs any extra information, please, tell me.
Thank you!

Accepted Answer

Sriram Tadavarty
Sriram Tadavarty on 22 Mar 2020
Edited: Sriram Tadavarty on 23 Mar 2020
Hi,
You can try the following:
x = rand(4,900);
y = rand(4,900);
sumOut = zeros(4,4); % Updated variable name to make it different from inbuilt function
for i = 1:900
tmp = x(:,i)-y(:,i);
R(:,:,i) = tmp*tmp';
sumOut = sumOut + R(:,:,i);
end
Hope this helps.
Regards,
Sriram
  2 Comments
Stephen23
Stephen23 on 22 Mar 2020
Naming a variable sum is not recommended because this shadows the inbuilt sum function.
Sriram Tadavarty
Sriram Tadavarty on 23 Mar 2020
Yes. you are right. Updated the variable with other name,

Sign in to comment.

More Answers (0)

Categories

Find more on Fourier Analysis and Filtering in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!