Search code examples
matlaboverloadingnumerical-methodssymbolic-math

Writing function for symbolic and numeric input


I am writing a (rather big) pure function, which shall accept numeric and symbolic input. The problem I am facing is (mostly) with conversion symbolic expressions to logical expression. E.g., When I have a expression like syms x; assume( x, 'positive' ); and a test if( x>0 ); ..., then Matlab throws an error; Either:

    Conversion to logical from sym is not possible.

or

    Unable to prove 'x > 0' literally. Use 'isAlways' to test the statement mathematically.

depending on the context.

Up to now I solved this problem by rewriting all my ifs to if( isAlways(x>0) ); ... and adding a function isAlways in a folder @double, so that Matlab uses this function when it encounters a double.

The downside of this approach is, that I would have to write a isAlways function for each other type too (single, int8, ... ) (and also functions simplify,...).

Another approach of mine was, to write a function isAlways in the global namespace, and call the builtin isAlways when I encounter a sym. But, isAlways does not seem to be a built in, since Matlab reports

    >> builtin('isAlways',sym(1));
    Error using builtin
    Cannot find builtin function 'isAlways' 

Do you have any ideas how to solve this problem in a more elegant way, or at least another way?


Edit: I don't want to change the code of my function much, in particular don't want to add checks like switch class(x); case sym; ... case double;...`, but add "functionality" to Matlab such that it works out of the box for most functions.


Solution

    1. In Matlab version approx R2018 I ended up defined a function isAlways in a folder @double etc.
    2. Unfortunately, the behaviour changed around Matlab R2020. Now it is not possible anymore in a reliable way to add functions to classes. Thus, I now define a function isAlways in the global namespace, which gets called for each type which does not have an overload. This is not the perfect solution, but it works at least.