我正在 MATLAB 中研究一些 OOP。我目前正在创建一个类,如下所示:
classdef uavclass
properties
%all properties of the uav
position = [0,0,0]
charge = 100;
destination = [0,0,0];
maxVertClimb = 2;
maxHorizSpeed = 5;
sensorRange = 25;
unloadingTime = 60;
safeDistance = 5;
chargingTime = 300;
minCruiseAlt = 20;
maxCruiseAlt = 70;
end
methods(Static)
function uav = uavclass(x,y,z)
uav.position = [x,y,z]
end
end
end
我可以通过调用以下命令在位置
创建一个无人机
:
uav1 = uavclass(20,20,0);
uav2 = uavclass(40,40,0);
uav3 = uavclass(50,50,0);
uav4 = uavclass(80,80,0);
uav5 = uavclass(90,90,0);
每当我尝试在 uav
对象上使用任何类型的方法时,我都会收到错误。一个例子是简单地尝试更改某些uav
sensorRange
function changesense(b)
uav.sensorRange = b
end
也尝试过uavclass.sensorRange
。我尝试使用 uav1.changesense(5)
调用它,但它不会更改该值。我还尝试过使用和不使用 (Static)
方法,以及 changesense(uav1,b)
等。
我做错了什么?
最佳答案
每个方法都必须有第一个参数来定义要修改的对象。这意味着,您需要像这样实现它:
function obj = changesense(obj, b)
obj.sensorRange = b
end
这只是它在 MATLAB 中的工作原理。 另请参阅此处的一些简单的 OOP 示例: https://de.mathworks.com/help/matlab/matlab_oop/getting-familiar-with-classes.html这个文档关于不同类型的方法:https://de.mathworks.com/help/matlab/matlab_oop/specifying-methods-and-functions.html#brqy87j 如果您想使用静态方法(不在对象的上下文中工作,则不需要第一个参数)。
它与Python中的self
是相同的概念。
您想了解的有关 Matlab 中 OOP 的所有内容都已完整记录在该主页的任何子页面中:https://de.mathworks.com/help/matlab/object-oriented-programming.html
关于Matlab - OOP 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37223904/