基本的matlab类方法 [英] Basic matlab class method
问题描述
可能重复:
如何修改Matlab对象的属性
我试图将我的C#代码转换成Matlab,在Matlab中我决定使用OOP,我没有使用Matlab,能够处理我的C#代码的复杂性。
I'm trying to convert my C# code into Matlab, in Matlab I decided to use OOP, which I haven't been used with Matlab, to be able to handle with the complexity of my C# code.
查看教程,我想出了以下代码:
Looking the tutorial, I come up with the following code:
classdef Cat
properties
meowCount = 0;
end
methods
function Meow(C)
disp('meowww');
C.meowCount = C.meowCount + 1;
end
end
end
结果:
>> c = Cat();
>> c.Meow();
meowww
>> c
c =
Cat
Properties:
meowCount: 0
Methods
因此, meowCount
不会更改。问题是什么?
So, meowCount
does not change. What is the problem?
推荐答案
我注意到一些问题:
- 您没有构造函数
- 您不是从
句柄派生
基类
- you have no constructor
- you do not derive from the
handle
base class
构造函数不是绝对必要的,但是当你真正想开始开发更大的类时,非常有用。它用于初始化 obj
对象,它会传递给每个方法。它非常类似于Python的 self
,或C ++的 this
。
The constructor is not strictly necessary, but very useful to get to know for when you really want to start developing larger classes. It is used to initialize the obj
object, which gets passed around to each and every method. It is quite similar to Python's self
, or C++'s this
.
因此,您修正的类:
classdef Cat < handle
properties
meowCount = 0;
end
methods
function obj = Cat()
% all initializations, calls to base class, etc. here,
end
function Meow(obj)
disp('meowww');
obj.meowCount = obj.meowCount + 1;
end
end
end
演示:
>> C = Cat;
>> C.Meow;
meowww
>> C.meowCount
1
这篇关于基本的matlab类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!