What am I doing wrong with object oriented programming?

1 view (last 30 days)
This is hopefully a very straight forward problem. I've tried looking through the documentation, but everything I'm doing seems legit so here I am.
I have a .m file ParticleInBox.m
classdef ParticleInBox
properties
end
methods
function q = calculateSin(x)
q = sin(x);
end
end
If I try
>> p = ParticleInBox();
>> p.calculateSin(2.0)
Error using ParticleInBox/calculateSin
Too many input arguments.
Any ideas why it is complaining about too many input arguments?
Thanks!
Mark

Accepted Answer

Sven
Sven on 15 Sep 2013
Edited: Sven on 15 Sep 2013
Mark, you're almost there. Here's how to "just get it running":
methods
function q = calculateSin(this, x)
q = sin(x);
end
end
Note that I've added an argument to your function. The first argument of all functions of a class will be the instance of that class being called. So when you call:
>> p = ParticleInBox();
>> p.calculateSin(2.0)
The second line is actually equivalent to:
calculateSin(p,2.0)
One way to think of what happens is that MATLAB basically checks the first argument of every call to a function. If that first argument is an object (as in your case, the object is p), and that object is of a class that has a method equivalent to the function being called (in your case the object p is of the class ParticleInBox, which has a method called calculateSin), then MATLAB will call that method, giving the object itself (ie, p) as the first argument.
So to answer your question, your original function signature had only one argument, which is by default the object (even though you used the variable name x). When you called the function with a second argument 2.0 you gave it more arguments than it expected.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!