MATLAB: Distance difference from center

distance

ML2.jpg
Hi,
I created a cross section by using kmeans function from two different data (indicated by X and * in image),
My aim is to determine the distance difference of two data from center (o) of cross section,
Briefly i try to find the;
Distance between O and X (d1)
Than i need to find the nearest * to X,
Than calculate the distance between O and * (which is nearest X) (d2)
And lastly i need to calculate the difference between (d1) and (d2)
And i want to do this calculations for all X to * in cross-section.
Thank you…
My current code is given below: my points are represented by m,n and o in code…
clc;clear;
x=xlsread('king1.xlsx', 'A:A');
y=xlsread('king1.xlsx', 'B:B');
z=xlsread('king1.xlsx', 'C:C');
a=xlsread('king2.xlsx', 'A:A');
b=xlsread('king2.xlsx', 'B:B');
c=xlsread('king2.xlsx', 'C:C');
xyz=[x y z];
abc=[a b c];
rng(1);
[idx1,C1] = kmeans(xyz,100,'distance','sqEuclidean','MaxIter',500, 'Replicates', 10);
[idx2,C2] = kmeans(abc,100,'distance','sqEuclidean','MaxIter',500, 'Replicates', 10);
[dist,idx3] = pdist2(xyz, C1, 'euclidean', 'Smallest',1);
newVar = xyz(idx3 ,:);
plot3(newVar(:,1), newVar(:,2), newVar(:,3), 'bx');
hold on;
xlabel ('x – axis', 'fontsize', 12);
ylabel ('y – axis', 'fontsize', 12);
zlabel ('z – axis', 'fontsize', 12);
grid
[dist2,idx4] = pdist2(abc, C2, 'euclidean', 'Smallest',1);
newVar2 = abc(idx4 ,:);
plot3(newVar2(:,1), newVar2(:,2), newVar2(:,3), 'r*')
newVar3 = mean (newVar)
newVar4 = mean (newVar2)
newVar5 = (newVar3 + newVar4)/ 2
plot3(newVar5(:,1), newVar5(:,2), newVar5(:,3), 'go');
m=[newVar(:,1) newVar(:,2) newVar(:,3)];
n=[newVar2(:,1) newVar2(:,2) newVar2(:,3)];
o=[newVar5(:,1) newVar5(:,2) newVar5(:,3)];

Best Answer

I did this
xyz0 = (mean(xyz)+mean(abc))/2; % O point
XYZ0 = repmat(xyz0,size(xyz,1),1); % duplicate rows

d1 = XYZ0 - xyz; % Distance(s) between O and X (d1)
% find the nearest * to X
D = pdist2(xyz,abc); % every possible combinations
D(D==0) = max(D(:)); % fill zeros with max ( (:) - convert matrix to column vector )
[~,ind] = min(D(:)); % find index of min element
% Found index of min element in vector. Find correspoding indices of points
[i,j] = ind2sub(size(D),ind); % extract row and column (i - index of xyz, j - index of abc)
% calculate the distance between O and * (which is nearest X) (d2)
d2 = xyz0 - abc(j,:); % difference between O point and * (nearest X)
D2 = repmat(d2,size(d2,1),1); % duplicate rows
d = D2 - d1; % distance(s) between d2 and d1