Property Validation fails due to assignment issues.
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hey everyone,
I'm trying to implement some property validation function for a class as follows
classdef test
properties
Str {mustBeString(Str)}
end
methods
function obj = test(str)
obj.Str = str;
end
end
end
function mustBeString(str)
% MUSTBESTRING checks if argument is a string
if ~isstring(str) && ~ischar(str)
error('Parameter:wrongType',...
'Description must be string.');
end
end
But here's the problem. It doesn't matter which value or type Str has, because matlab seems to assign an empty value for this property even before the constructor is evaluated. In fact I checked in debugging mode and it seems that the validation function is called before the constructor.
I also tried to execute a modified example from the matlab documentation
classdef ImData
properties
Data {mustBeNumeric, mustBeInRange(Data,[0,255])}
end
methods
function obj = ImData(dat)
obj.Data = dat;
end
end
end
function mustBeInRange(a,b)
if any(a(:) < b(1)) || any(a(:) > b(2))
error(['Value assigned to Data property is not in range ',...
num2str(b(1)),'...',num2str(b(2))])
end
end
In this case everything worked fine.
Anyone who might have an idea, how to fix this issue?
Thank you very much.
0 comentarios
Respuestas (1)
Nirav Sharda
el 18 de Abr. de 2017
The documentation page of Property Validation mentions that you should add a default value. Also in the example mentioned in the document they have set the default value of the Data which is numeric to 0. You can in your case set it to empty string or char array. You can modify your code to:
Str {mustBeString(Str)} = ''
I hope this helps.
0 comentarios
Ver también
Categorías
Más información sobre Argument Definitions en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!