What am I doing wrong with object oriented programming?

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Sven
Sven il 15 Set 2013
Modificato: Sven il 15 Set 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.

Più risposte (0)

Categorie

Scopri di più su Get Started with MATLAB in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by