Please show using MATLAB 2·The distance between two points in three-dimensional
ID: 2249117 • Letter: P
Question
Please show using MATLAB
2·The distance between two points in three-dimensional space is where point 1 has coordinates (x, y, z,) and point 2 has coordinates (x2, y2, z). For each point the x, y, z coordinates are stored in a vector of length 3. Write a MATLAB function named dist which computes the distance between two points. The arguments to the function are the two vectors containing coordinates. The result returned is the distance. Include comments in the function. The following are examples of the function being used. 22'Explanation / Answer
%code written can be used for N dimensional points also
function distance1 = dist(point1,point2)
N = length(point1);%determines the dimension
sum1 = 0;
for i=1:N
sum1 = sum1+(point1(i)-point2(i))^2;%sums the all values under the square root
end
distance1 = sqrt(sum1);%square root of sum gives the distance between two points
end
Command window log:
>> clear all
>> point1 = [1 3 7];
>> point2 = [1 3 8];
>> point3 = [2 4 8];
>> d1 = dist(point1,point2)
d1 =
1
>> d2 = dist(point1,point3)
d2 =
1.7321
>> d3 = dist(point1,point1)
d3 =
0
>> point4 = [1 2 3 4];
>> point5 = [3 5 8 7];
>> d4 = dist(point4,point5)
d4 =
6.8557
>>