Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

MatLab question about Methods

  1. Dec 24, 2011 #1
    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
     
  2. jcsd
  3. Dec 24, 2011 #2

    Pythagorean

    User Avatar
    Gold Member

    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.
     
  4. Dec 24, 2011 #3
    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.
     
  5. Dec 24, 2011 #4
    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
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: MatLab question about Methods
Loading...