Is there a built-in function to validate a class property that should be a cell array?

조회 수: 16(최근 30일)
I'm new to classes and learning about how to define properties and validate their values.
I have a class with a property A that is a cell array of doubles (possibly matrices). For example:
A =
1×2 cell array
{[0.7000]} {[0.9000]}
classdef MKFObserver < matlab.mixin.Copyable
properties (SetAccess = immutable)
Ts {mustBeNumeric}
n {mustBeInteger}
A % how to validate this?
P {mustBeNumeric}
Q {mustBeNumeric}
R {mustBeNumeric}
Can I use a built in function like {mustBeNumeric} or do I need to write my own validation function?
  댓글 수: 3
per isakson
per isakson 2022년 6월 4일
Something like this
A (1,2) {mustBeUnderlyingType(A,'cell')}
Not tested

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

채택된 답변

Edric Ellis
Edric Ellis 2022년 6월 6일
Rather than a validator, you could perhaps just use the class specification? (In my code below I'm using a function with an arguments block, but the syntax is exactly the same as a properties block in a classdef). Note that this will accept anything that can be converted to a cell, if you care about distributed arrays, then you should use the approach suggested by @Sean de Wolski.
myFcn({1,2}); % works
myFcn([1,2]); % fails
Error using solution>myFcn
Invalid argument at position 1. Value must be of type cell or be convertible to cell.
function myFcn(in)
in (1,2) cell
% do stuff
  댓글 수: 1
Bill Tubbs
Bill Tubbs 2022년 6월 6일
편집: Bill Tubbs 2022년 6월 6일
This worked! I just did this:
classdef MKFObserver < matlab.mixin.Copyable
A cell
B cell
% Test:
>> MKFObserver([0.7 0.9], ...)
Error setting property 'A' of class 'MKFObserver':
Invalid data type. Value must be cell or be convertible to cell
It doesn't check the underlying type of the elements of the cell array but I decided in the end I don't want this level of validation. Thanks.

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

추가 답변(2개)

Matt J
Matt J 2022년 6월 4일
편집: Matt J 2022년 6월 4일
There is always iscell():
function obj=set.A(obj,A)
assert(iscell(A),'Value assigned to A must be cell array');

Sean de Wolski
Sean de Wolski 2022년 6월 5일
편집: Sean de Wolski 2022년 6월 5일
I think you'll have to write your own. Must be underlying type is for distributed, gpuArrays and others that masquerade as the underlying type.
Value must have underlying type 'double'.
You could probably get away with this as your validator: cellfun(@(x)mustBeA(x, 'double'),PropertyName)
c = {pi,magic(3)}
d = {pi, "hello"}
cellfun(@(x)mustBeA(x, 'double'),c)
cellfun(@(x)mustBeA(x, 'double'),d)


Find more on Argument Definitions in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by