What am I doing wrong with object oriented programming?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Sven
le 15 Sep 2013
Modifié(e) : Sven
le 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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!