What am I doing wrong with object oriented programming?

조회 수: 2(최근 30일)
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
function q = calculateSin(x)
q = sin(x);
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?

채택된 답변

Sven 2013년 9월 15일
편집: Sven 2013년 9월 15일
Mark, you're almost there. Here's how to "just get it running":
function q = calculateSin(this, x)
q = sin(x);
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:
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.
  댓글 수: 1
Mark 2013년 9월 15일
Excellent answer! Thanks a lot Sven.

댓글을 달려면 로그인하십시오.

추가 답변(0개)


Find more on Software Development Tools in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by