What am I doing wrong with object oriented programming?

조회 수: 3 (최근 30일)
Mark
Mark 2013년 9월 14일
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

채택된 답변

Sven
Sven 2013년 9월 15일
편집: Sven 2013년 9월 15일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by