Dan Pollard
Dan Pollard

Reputation: 388

Matlab: How do I call a function which I have defined within a class?

I'm trying to learn how to use classes in Matlab, having never used them in any language before, so apologies if this is a bit basic.

I have defined a class called car, with the properties of colour, type, serial number and speed, with a function to change the speed.

classdef car <handle
   properties
      colour
      type
      speed
   end 
   properties (SetAccess = private)
      SerialNumber
   end
   methods
       function faster(obj, v)
           obj.speed = obj.speed + v;
       end
   end
end

In another script I can type

car.colour = "red", and when I disp(car), the class has the property colour with label "red". When I call faster(100) however, instead of setting car.speed=100, it throws the error

Check for missing argument or incorrect argument data type in call to function 'faster'.

I built the class and method using the same sort of code structure as in this question:

https://www.mathworks.com/matlabcentral/answers/395472-how-to-call-a-method-from-a-class-called-a-within-another-method-from-a

where the user seemed to not have the issue I do. I'm not sure where I'm going wrong - my function seems like it should work. Can anybody point me in the right direction?

Upvotes: 2

Views: 1634

Answers (1)

Wolfie
Wolfie

Reputation: 30047

You need to call the function on the class

myCar = car();
myCar.faster( 10 ); % equivalent to 'faster( myCar, 10 )'

If you hadn't specified the < handle type, you would also need to assign it back to the class, i.e.

myCar = myCar.faster( 10 );

But you don't need this with a handle class.

Upvotes: 1

Related Questions