Home > Blockchain >  How to do a table property validation in Matlab?
How to do a table property validation in Matlab?

Time:12-04

When I create an object in a constructor, myTable property is constructed on the fly, for example, from csv file. I want to have some validation for that property as I have for myInt. Do you happen to know how to do that? In the future, I guess I will need a per-column validation...

classdef BigObject 

  properties
  
    myInt (1,1) double {mustBeNonnegative, mustBeInteger} = 0;

    myTable (?,?) table {mustBeGreaterThan(table{1}.Variables,1), mustBeLessThan(table{2} ? ,2)} = table;


I tried selecting columns

    myTable table {mustBeGreaterThan(table{1},1)} = table;
    myTable table {mustBeGreaterThan(table{2}.Variables,2)} = table;
    myTable table {mustBeGreaterThan(table.Variables,3)} = table;

CodePudding user response:

The best way to achieve this is to write your own simple property validation function. You can build this on top of existing functions. So, you might do something like this:

%% Base case - passes
t = table((1:10).', 'VariableNames',{'MyVar'});
someFcn(t);

%% Fails because value is negative
t2 = table(-(1:10).', 'VariableNames',{'MyVar'});
someFcn(t2)

% Example function that uses validation
function someFcn(t)
arguments
    t {mustHavePositiveVar(t, 'MyVar')}
end
end
% Custom validation function
function mustHavePositiveVar(t, varName)
try
    mustBeA(t, 'table');
    mustBeMember({varName}, t.Properties.VariableNames)
    mustBePositive(t.(varName));
catch E
    error('Input must be a table with a variable named %s that is all positive', varName)
end
end

Note there's a nuance if you use the class constraint syntax at the same time as a property validation function - namely that the property gets assigned and type-coerced before the validation functions run. So if you're going to validate the type of an input, you need to omit the class constraint (otherwise the input might simply be coerced to the correct type anyway).

  • Related