I found some related questions, but didn't really find an answer in there.
I'm writing a simple little MATLAB class in order to learn OOP syntax in MATLAB. I'm very familiar with Python, and pulling my hair out trying to work with MATLAB. Here's the definition:
classdef Car < handle
properties
speed = [0,0] %x,y velocity
position = [0,0]
running = false
end
methods
function obj = Car(pos, spd)
obj.position = pos;
obj.speed = spd;
end
function accelerate(obj,x,y) % Add to speed
obj.speed = obj.speed + [x,y]
end
function position = getPosition(obj)
position = obj.position
end
function start(obj)
obj.running = true
end
function stop(obj)
obj.running = false
end
end
end
This is certainly not done, but then I'm using a little script to mess with the object:
foo = Car([1,1],[0,2])
foo.start
foo.accelerate(2,3)
Instantiation works, but ANY method I call throws an error. foo.start, for example:
Error using Car/start
Too many input arguments.
What am I missing??
Since I can't figure out how to delete this question, I'll do my best to answer it. Like other languages, object oriented programing in MATLAB wants to see obj
as the first parameter in class methods (like self
in python). This reference to the object is necessary to modify its attributes. I was not including this in method definitions, so when I called the method I was getting the "too many arguments" error. That's because if you do foo.method(a,b)
, then the object foo
is actually passed as a parameter, so you function is actually getting 3 inputs, i.e. method(foo,a,b)
.
I went through my code and added obj
in the appropriate places, but FAILED TO USE THE clear
COMMAND in the MATLAB command window. Since I'm new to MATLAB, I was unaware of its importance. I just assumed saving the file and re-instantiating my class would be sufficient. It is not.
I hope this helps anybody who comes across this question.
You don't need to pass the obj to the input if you declare the methods as static:
classdef class1
methods (Static)
function y=aPLUSb(a,b)
y=a+b;
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With