- Subclass of handle. This makes your life easier;
- obj is 'this'. All the none-static methods need to use obj as the first argument.
A question about Matlab class
1 次查看(过去 30 天)
显示 更早的评论
My question is demonstrated as in the attached code. The problem is that the code responds are not as I expected. In selfTest() function, I set the variable b = a, where a is a local variable of the function MyClass.selfTest(). But actually b is set to be "this" obj (the object a in the function TestMyClass()). What is wrong here?
In all the functions I used an input argument "obj". Without this "obj" as the argument, an error message "Too many input arguments" will be generated. What is wrong again?
Any help would be appreciated!
============================================================
function TestMyClass()
a = MyClass(magic(3)', [1 0 0]); %% this line runs fine
a.mat() %% 'Too many input arguments.' error
a.vec %% 'Too many input arguments.' error
a.selfTest(); %% 'Too many input arguments.' error
end
-------------------------------------------------------------------------------------------------------
classdef MyClass
properties (GetAccess = protected, SetAccess = protected)
m_myMat = eye(3);
m_myVec = zeros(1,3);
end
methods
function obj = MyClass(aMat, aVec) % constructor with parameters
m_myMat = aMat;
m_myVec = aVec;
end
function setMat(obj, aMat)
obj.m_myMat = aMat;
end
function setVec(obj, aVec)
obj.m_myVec = aVec;
end
function aMat = mat(obj)
aMat = obj.m_myMat;
end
function aVec = vec(obj)
aVec = obj.m_myVec;
end
function selfTest(obj) %% 'Too many input arguments.' error before entering this line
a = MyClass(eye(3), ones(1,3));
b = a;
b.setMat(magic(3));
b.setVec([0 0 1]);
b.mat() %% This line displays eye(3) instead of magic(3)
b.vec() %% This line displays [0 0 0] instead of magic(3)
end
end %% end of methods
end %% end of classdef MyClass
0 个评论
采纳的回答
Yongjian Feng
2021-11-1
Several issues here.
classdef MyClass <handle
properties (GetAccess = protected, SetAccess = protected)
m_myMat = eye(3);
m_myVec = zeros(1,3);
end
methods
function obj = MyClass(aMat, aVec) % constructor with parameters
obj.m_myMat = aMat;
obj.m_myVec = aVec;
end
function setMat(obj, aMat)
obj.m_myMat = aMat;
end
function setVec(obj, aVec)
obj.m_myVec = aVec;
end
function aMat = mat(obj)
aMat = obj.m_myMat;
end
function aVec = vec(obj)
aVec = obj.m_myVec;
end
function selfTest(obj)
% What do you want to do here?
end
end %% end of methods
end %% end of classdef MyClass
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!