Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn off "smart behavior" in Matlab

There is one thing I do not like on Matlab: It tries sometimes to be too smart. For instance, if I have a negative square root like

a = -1; sqrt(a)

Matlab does not throw an error but switches silently to complex numbers. The same happens for negative logarithms. This can lead to hard to find errors in a more complicated algorithm.

A similar problem is that Matlab "solves" silently non quadratic linear systems like in the following example:

A=eye(3,2); b=ones(3,1); x = A \ b

Obviously x does not satisfy A*x==b (It solves a least square problem instead).

Is there any possibility to turn that "features" off, or at least let Matlab print a warning message in this cases? That would really helps a lot in many situations.

like image 806
Boris Avatar asked Dec 14 '11 13:12

Boris


1 Answers

I don't think there is anything like "being smart" in your examples. The square root of a negative number is complex. Similarly, the left-division operator is defined in Matlab as calculating the pseudoinverse for non-square inputs.

If you have an application that should not return complex numbers (beware of floating point errors!), then you can use isreal to test for that. If you do not want the left division operator to calculate the pseudoinverse, test for whether A is square.

Alternatively, if for some reason you are really unable to do input validation, you can overload both sqrt and \ to only work on positive numbers, and to not calculate the pseudoinverse.

like image 128
Jonas Avatar answered Oct 23 '22 04:10

Jonas