How to Correct Syntax for a Distance Calculation Method in MatLab?

  • Context: MATLAB 
  • Thread starter Thread starter Zoobie
  • Start date Start date
  • Tags Tags
    Matlab
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
Zoobie
Messages
3
Reaction score
0
I was tasked with creating a simple program to model the solar system using Matlab. One step in the way I wanted to do this was by making a "planet" class that stored the x,y,z position, and the x,y,z velocity.

One of the methods, then, would be something to that took in another "planet" object and computed the distance between them. This is easy enough to do, but I can't figure out what the syntax is.

I have:

function [dist] = distanceTo(obj)
dist = sqrt(abs(obj.x - x)^2 + abs(obj.y- y)^2 + abs(obj.z-z)^2);
end

My intention here is that obj will be an inputted planet, and typing obj.x will give you its x-value. This however isn't the case, and whenever I try to run it I get a "Too many inputs error"

Can anyone help me figure out the correct syntax? Thanks for any help and happy holidays
 
Physics news on Phys.org
tell us the command line or code line that you call the function with. Also, I see nowhere that your program is going to get x,y, and z from.
 
That's just the function code. There is also a constructor method:

function p = planet(x_pos,y_pos,z_pos,x_vel,y_vel,z_vel,mass)
p.x = x_pos;
p.y = y_pos;
p.z = z_pos;
p.xV = x_vel;
p.yV = y_vel;
p.zV = z_vel;
p.mass = mass;
end

So the command line I type in is:

p = planet(1,2,3,4,5,6,7); p.distanceTo(p); (Edit: I would hope this returned zero).

This returns a "Too many inputs error".

Thanks for any help

Edit: Also in regards to where it gets x,y, and z from - Those are properties in the class. I think I remember in java typing this.(variable name) to reference a variable in the class, but I'm not sure what the equivalent would be in Matlab.
 
I actually made some progress on it - I changed the parameters of the function to:

function [dist] = distanceTo(obj,obj2)
dist = sqrt(abs(obj.x-obj2.x)^2 + abs(obj.y - obj2.y)^2 + abs(obj.z + obj2.z)^2);
end

and typing in the same line returned the expected outcome. My question then turns to is "obj" the self referencing line, while "obj2" is the other "planet" object? From what I can tell this is how it works.

Thanks again