How do I assign variables to coordinate values?

44 views (last 30 days)
Jacob
Jacob on 28 Sep 2014
Commented: Jacob on 28 Sep 2014
So basically I have two points on a 3-D graph, (x1, y1, z1) and (x2, y2, z2). My task is to find the distance between the points using the formula ((x1 - x2)^2 + (y1 - y2)^2 + (z1 - z2)^2)^.5)
I'm using a fprintf script for the formula, and input scripts saying "enter the coordinates of point 1 in the form of [x1, y1, z1]" and "enter the coordinates of point 2 in the form of [x2, y2, z2]"
I'm wondering what I need to do to write a script that will automatically compute the user's input coordinates, so that no matter what value they type in it will automatically compute the distance.
For the assignment, the points are [-3, 2, 5] and [3, -6, -5], this is all I have for script:
point1 = input('Enter the coordinates of point 1 in the form [x1, y1, z1]: ')
point2 = input('Enter the coordinates of point 2 in the form [x2, y2, z2]: ')
fprintf('The distance between the two points is %d\n', ((x1 - x2)^2 + (y1 - y2)^2 + (z1 - z2)^2)^.5)
Thanks for the help!

Answers (1)

Geoff Hayes
Geoff Hayes on 28 Sep 2014
Jacob - once the user has entered the two example vectors, then both point1 and point2 are 1x3 arrays/vectors. If you wish to use your fprintf statement from above, then ask yourself, what is x1? It is the x-coordinate of the first point...which is simply point1(1). What is y1? It is the y-coordinate of the first point...which simply point1(2). Etc. So you can replace your x's, y's, and z's in your fprintf with their equivalent values from the two arrays. Or assign the variables given the coordinate values as
x1 = point1(1);
x2 = point2(1);
% etc.
Alternatively, you can avoid creating local variables for all elements in your two vectors and calculate a sum of the squared differences between corresponding elements of the two vectors. Try this as well, using a for loop to iterate over each element adding that squared difference to that which was calculate on the previous iteration.

Categories

Find more on Creating and Concatenating Matrices 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!