views:

181

answers:

2

In Matlab when one tries to access an element of a matrix that doesn't exist usually an error is raised:

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

I was wondering whether there is a function that allows supplying default value in such cases. E.g.,:

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

P.S. I can workaround this particular case of subscript (0), but I was wondering about more generic way of doing this.

+2  A: 

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

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

a =

   NaN

However, the best option would probably be to error-check the index first, throwing an error or setting a variable to a default value if it is out of range.

If you really want to try using an index that may be 0, you could write your own get_def function. Here's one way to do it:

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

You would then use this function in the following way:

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

ans =

   NaN

>> get_def(month,1,nan)

ans =

     1
gnovice
I'm just commenting to say that I love your icon. Yay QOTSA!
Matt Grande
@Matt: Thanks! You're only the second person to notice/mention it.
gnovice
I just happened to be listening to a live QOTSA album when I stumbled on this. Thanks for completing the sensory picture.
b3
+3  A: 

An elegant solution would be to create a subclass of the builtin double MATLAB class and overload the subsref method:

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

You could then use this class as follows:

>> 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

Since the subclass inherits from the double class, you still get all the functionality of the double class and the added functionality of your custom myDouble class.

Check out the MATLAB help on:

b3
+1: I actually considered making this suggestion, but thought it might be a little more complexity than what the OP was looking for.
gnovice
I hope the OP is encouraged to explore MATLAB classes. You're correct that it may be more complex initially but solving problems using can become a lot easier even with a beginner's understanding of OOP concepts. Of course, used inappropriately, programs can also become Rube Goldberg-ian!
b3

related questions