フィルターのクリア

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 Center および File ExchangeProperties についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by