Function Argument Validation: Comparing property size to a variable
Afficher commentaires plus anciens
I would like to ensure that a property of a class is of a certain size, defined by another property of the class which is set in the constructor. I can implement this by using a private property and set and get methods as shown in the code example below:
classdef TestClassI < handle
properties(SetAccess=immutable)
matrixSize single
end
properties(Dependent)
matrix single {mustBeNumeric}
end
properties(Access=private, Hidden=true)
matrix_
end
methods
function obj = TestClassI(matrixSize)
obj.matrixSize = matrixSize;
end
function matrix = get.matrix(obj)
matrix = obj.matrix_;
end
function set.matrix(obj, val)
validateattributes(val, {'numeric'}, {'size', obj.matrixSize});
obj.matrix_ = val;
end
end
end
However, this is pretty cumbersome. What I'd prefer to do is something like:
classdef TestClassII < handle
properties(SetAccess=immutable)
matrixSize single
end
properties
matrix(10,1) single {mustBeNumeric}
end
methods
function obj = TestClassII(matrixSize)
obj.matrixSize = matrixSize;
end
end
end
But, where (10,1) is not hard-coded but given by matrixSize. Is there a way to do this?
Réponse acceptée
Plus de réponses (1)
Shubham
le 29 Mai 2023
Hi Bradley,
Yes, there is a way to achieve this without the use of set and get methods. One possible solution is to use the validateattributes function in the constructor to check that the matrix property has the correct size. Here's an example implementation:
classdef TestClassII < handle
properties(SetAccess=immutable)
matrixSize single
end
properties
matrix single {mustBeNumeric}
end
methods
function obj = TestClassII(matrixSize)
obj.matrixSize = matrixSize;
defaultSize = [matrixSize, 1];
defaultMat = zeros(defaultSize, 'single');
validateattributes(defaultMat, {'numeric'}, {'size', defaultSize});
obj.matrix = defaultMat;
end
end
end
In this implementation, we initialize the matrix property using a default size of [matrixSize, 1] and fill it with zeros using the zeros function. Then we use validateattributes to check that the size of the default matrix is correct.
Note that validateattributes raises an error if the validation fails, so we only set obj.matrix if the validation succeeds.
1 commentaire
Bradley Treeby
le 5 Sep 2023
Modifié(e) : Bradley Treeby
le 5 Sep 2023
Catégories
En savoir plus sur Properties 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!