Reputation: 7132
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.
Upvotes: 6
Views: 2039
Reputation: 5251
You need to understand all of the implications of what you're writing and make sure that you use the right functions if you're going to guarantee good code. For example:
realsqrt
insteadinv(A) * b
insteadOr alternatively, include the appropriate checks before/after you call the built-in functions. If you need to do this every time, then you can always write your own functions.
Upvotes: 3
Reputation: 74940
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.
Upvotes: 3