Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a null reference in matlab so that isa returns true?

I have a class Foo and a function that gets Foo as input parameter. In this function I also do some error checking using isa:

function (x)  
  if ~isa(x,'Foo')  
     error('Wrong!');  
  end

I want to pass it something that is like null in Java. However when I pass it [] I get an error. Can you tell me what can I do? I though about always passing a cell array or checking for empty everytime I use isa.

like image 781
Cloud Harrison Avatar asked Jan 18 '12 19:01

Cloud Harrison


1 Answers

First of all, you can check our condition with

  validParam = isa(x,'Foo') || isempty(x);

However, the best way will be to create an empty class using the static method empty:

  e = Foo.empty(0);
  isa(x,'Foo')

And the result is:

isa(Foo.empty(0),'Foo')

ans =

1  

By the way, this is also useful for another case - Suppose you want to grow dynamically and array of Foo objects. You could use a cell array, but then you lose the type safety. Instead, create Foo.empty() .

Nevertheless, there is a caveeat in using this method. It is not smart enough to handle inheritance -

Let Bar be a class that inherits from Foo.

classdef Bar < Foo

end

And you allocate a new array of Foo objects:

x = Foo.empty(0)

x =

0x0 empty Foo with no properties.
Methods

Then try to add Bar :

x(end+1) = Bar()

??? The following error occurred converting from Bar to Foo: Error using ==> Foo Too many input arguments.

So the only workaround for this case is to use cell array.


Edit(1): It seems that Matlab have added a special class in order to handle inheritance:

Description

matlab.mixin.Heterogeneous is an abstract class that provides support for the formation of heterogeneous arrays. A heterogeneous array is an array of objects that differ in their specific class, but are all derived from or are instances of a root class. The root class derives directly from matlab.mixin.Heterogeneous.

like image 56
Andrey Rubshtein Avatar answered Oct 19 '22 05:10

Andrey Rubshtein