MATLAB: Calcuer the disstance between all points

distancematrice linepoint

there are two matrix O1 and O2 of the same size 1 line and 5 columns, o1 o2 represante X and Y which represante 5 is obtained point-ordinates (o1 (i), a2 (j)) we will calcuer the disstance between all the points, and if lower 30 esy must make a line between them .I have problem in the code that can help me and thank you here is the code
o1 =[30 38 29 68 39]
o2 =[109 29 24 75 97]
plot(o1,o2,'^','LineWidth',1,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','y',...
'MarkerSize',12);
hold on
%calculate the distance between the point
for i=1:4
for j=1:4
% % d=sqrt[(x2-x1).^2 + (y2-y1).^2]
d(i,j)=sqrt([o1(i+1)-o1(i)].^2 + [o2(j+1)-o2(j)].^2)
i==i+1;
j==j+1;
end
end
% to test the value of and created a line if d <30
for i=1:4
for j=1:4
if d(i,j)<=30
line(o1(i),o2(j))
end
end
end

Best Answer

brini - if o1 and o2 are the x and y coordinates respectively of your five points, then your distance calculations can simplify to
d = zeros(5,5);
for i=1:5
for j=i+1:5
d(i,j) = sqrt((o1(i)-o1(j))^2 + (o2(i)-o2(j))^2);
d(j,i) = d(i,j);
end
end
Note how we pre-size the distance d matrix to be 5x5. We then iterate over each point calculating the distance between the two, (o1(i),o2(i)) and (o1(j),o2(j)). This is different from your distance calculation of
d(i,j)=sqrt([o1(i+1)-o1(i)].^2 + [o2(j+1)-o2(j)].^2)
which doesn't use the j value correctly when doing the subtraction. We subtract the x-components as o1(i)-o1(j) and the y-components as o2(i)-o2(j) before squaring each and then adding the two together. Since the distance between point i and j is the same as the distance between point j and i, then we can set
d(j,i) = d(i,j);
which saves us from doing a redundant calculation.
Now, when you want to draw a line between two points you need to use both the x and y components of those points. The code then becomes
for i=1:5
for j=i+1:5
if d(i,j)<=300
line([o1(i) o1(j)],[o2(i) o2(j)]); % supply both the x and y components
end
end
end
Try the above and see what happens!