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

4 ビュー (過去 30 日間)
Daniel Pollard
Daniel Pollard 2020 年 11 月 27 日
回答済み: Steven Lord 2020 年 11 月 27 日
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:
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?

採用された回答

Daniel Pollard
Daniel Pollard 2020 年 11 月 27 日
This question has now been answered on Stack Overflow:
https://stackoverflow.com/questions/65038867/matlab-how-do-i-call-a-function-which-i-have-defined-within-a-class.

その他の回答 (1 件)

Steven Lord
Steven Lord 2020 年 11 月 27 日
When you call a non-Static method of a class, at least one of the inputs to that method must be an instance of that class. With your car class's definition:
% Create a car
y = car
% Set its colour
y.colour = 'red'
% Set its initial speed
y.speed = 30
% Update the speed with the method
faster(y, 10)
% Alternately you could use
% y.faster(10)
% Display the updated object
y

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by