How to perform a single Matrix calculation and store result back into a vector or matrix

1 次查看(过去 30 天)
Hi, Everyone
I have written a code which calculates weighted distance in a single matrix. (similar to euclidean distance). I need to know how to store my results back into a matrix or vector instead of displaying it n times.
Here is my code
///////////////////////////
i=1;
j=2;
for i=1:4
for j=2:5
if((i~=j)&&(i<j))
d=0;
for k=1:6
sum=(data(j,k)-data(i,k))^2;
d=d+sum;
end
d=(0.25*d)^(1/2)
end
end
////////////////////
end
For example if I have a 5x6 matrix as given below
85 92 45 27 31 0
85 64 59 32 23 0
86 54 33 16 54 0
91 78 34 24 36 0
87 70 12 28 10 0
my results are displayed as
d =
16.3478
d =
23.6590
d =
9.8362
d =
22.4666
d =
22.3271
d =
16.5076
d =
24.6678
d =
15.7321
d =
26.3534
d =
17.7200
But I would like to store as
d=[ 16.3478; 23.6590; 9.8362; 22.4666; 22.3271; 16.5076; 24.6678; 15.7321; 26.3534; 17.7200]
Please If anyone could help me.

采纳的回答

Fangjun Jiang
Fangjun Jiang 2011-10-23
  1. "i=1; j=2;" is not needed based on your code.
  2. Don't use "sum" as the variable name. sum() is a built-in function.
Your code can be improved as the following:
data=rand(5,6);
[M,N]=size(data);
d=zeros(M*(M-1)/2,1);
count=0;
for i=1:M-1
for j=2:M
if((i~=j)&&(i<j))
count=count+1;
for k=1:N
d(count)=d(count)+(data(j,k)-data(i,k))^2;
end
d(count)=(0.25*d(count))^(1/2);
end
end
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by