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.
There is no built-in MATLAB function to do what you want. You could use a try-catch block:
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_deffunction. Here’s one way to do it:You would then use this function in the following way: