Disable Smart Behavior in Matlab

There is one thing about Matlab that I don't like: it sometimes tries to be too smart. For example, if I have a negative square root, for example

a = -1; sqrt(a) 

Matlab does not throw an error, but silently switches to complex numbers. The same thing happens with negative logarithms. This can make it difficult to find errors in a more complex algorithm.

A similar problem is that Matlab "resolves" silent, non-quadratic linear systems, as in the following example:

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

Obviously, x does not satisfy A*x==b (instead, it solves the least-square problem).

Is it possible to disable these features, or at least allow Matlab to print a warning message in this case? This helps a lot in many situations.

+6
source share
2 answers

I do not think that in your examples there is something like "smart". The square root of a negative number is complex. Similarly, the left division operator is defined in Matlab as the calculation of a pseudo-inverse for non-square input signals.

If you have an application that should not return complex numbers (beware of floating point errors!), You can use isreal to verify this. If you do not want the left division operator to calculate the pseudo-inverse, check if A square.

Alternatively, if for some reason you really cannot perform input validation, you can overload both sqrt and \ only to work with positive numbers and not calculate the pseudo-inverse.

+3
source

You need to understand all the consequences of what you write, and make sure that you use the right functions if you are going to guarantee good code. For instance:

  • In the first case, use realsqrt instead
  • For the second case, use inv(A) * b instead

Or, alternatively, enable the appropriate checks before / after calling the built-in functions. If you need to do this every time, you can always write your own functions.

+3
source

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


All Articles