A question about Matlab class
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Classification dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!