Is it possible to provide a default value for a subscription in Matlab?

In Matlab, when you try to access a matrix element that does not exist, an error usually occurs:

>> month(0)
??? Subscript indices must either be real positive integers or logicals.

I was wondering if there is a function that allows you to provide a default value in such cases .. For example,

>> get_def(month(0), NaN)
ans =
   NaN

PS I can get around this particular case of index ( 0), but I was interested to know about this more general form.

+3
source share
2 answers

There is no built-in MATLAB function to do what you want. You can use a try-catch block :

>> try a = month(0); catch a = nan; end
>> a

a =

   NaN

, , , , .

, 0, get_def. :

function value = get_def(vector,index,defaultValue)
  try
    value = vector(index);
  catch
    value = defaultValue;
  end
end

:

>> month = 1:12;
>> get_def(month,0,nan)

ans =

   NaN

>> get_def(month,1,nan)

ans =

     1
+2

double MATLAB subsref:

classdef myDouble < double

    methods

        function obj = myDouble(val)
            obj = obj@double(val);
        end

        function val = subsref(obj, S)
            try
                val = subsref@double(obj, S);
            catch
                val = NaN;
            end
        end

    end

end

:

>> a = myDouble(1:10);
>> a(1:3)

ans = 
  myDouble
  double data:
     1     2     3

  Methods, Superclasses

>> a('asdsa')

ans =
   NaN

>> a({1, 'asdf'})

ans =
   NaN

double, double myDouble > .

MATLAB:

+3

Source: https://habr.com/ru/post/1715084/


All Articles