필터 지우기
필터 지우기

A question about Matlab class

조회 수: 1 (최근 30일)
Ming Chao
Ming Chao 2021년 11월 1일
댓글: Ming Chao 2021년 11월 5일
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

채택된 답변

Yongjian Feng
Yongjian Feng 2021년 11월 1일
Several issues here.
  • Subclass of handle. This makes your life easier;
  • obj is 'this'. All the none-static methods need to use obj as the first argument.
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
  댓글 수: 1
Ming Chao
Ming Chao 2021년 11월 5일
Your answer helped solve my problems. Thanks Yongjian!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Properties에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by