Matlab - what is equivalent to null / None / nil / NULL etc.?

In most OO languages, where variables can point to objects, they can also have a null value, which is very convenient.

In Matlab, I have a function that parses a command and then returns an array of cells or false (which is zero - this is another common pattern) if it fails:

 function re = parse(s) ... if (invalid) re = false; return; end end 

The problem is that when I check the result, it gives an error:

 re = parse(s); if (false == re) Undefined function 'eq' for input arguments of type 'cell'. 

I wrote a function for checking without errors: strcmp('logical', class(re)) && false == re , but it seems very slow to use in hot areas of the code, and also inconvenient if I need to add this function to each file M I am writing.

Using NaN even worse because, in addition to throwing this error, it is also not equal to itself.

What is the best alternative to use with this template?

+6
source share
5 answers

You can use the isequal function to compare any two elements without causing this error. For instance:

 if isequal (re, false) %code here end 
+3
source

A good alternative is to use an empty array: [] and isempty(re) for checking. This does not cause an error.

Link: http://www.mathworks.com.au/matlabcentral/newsreader/view_thread/148764

+2
source

If you can change the parse function, one solution would be to return two output arguments [re status] = parse(s) , where status will be a boolean variable. Set to true if successful, otherwise false.

+1
source

I would use an empty array of cells {} if it is not a valid result. Using empty matrices is the MATLAB standard (see Evgeny Sergeyev's answer), but using an empty array cell instead of an empty numeric array ensures that you always get the same result.

If, on the other hand, an empty array of cells {} is a valid result of your function, then I would use an exception to signal a problem:

 if invalid error('Parse:InvalidArgumentError', 'The input is invalid.'); end 

Be sure to use the appropriate error identifier (the first argument to error ) so that you can precisely catch this exception when calling the function:

 try: result = parse(something); catch ME if strcmp(ME.identifier, 'Parse:InvalidArgumentError') fprintf('Ooops\n'); else % Some other error ME.rethrow(); end end 
+1
source

I think the problem is that matlab functions do not return pointers, but copies of values.

IMHO the best best approach would be to define your own class "pointer". Inside you can define the "isNull ()" command or even override the comparison to get the desired behavior.

0
source

All Articles