Search code examples
matlabsymbolic-math

MATLAB symbolic output with element-wise operations


Is there a function or technique for converting MATLAB's symbolic expressions to expressions that can be evaluated element-wise?

As an example, the command

a = solve('x^2 + a*x + b == 0')

gives the output

a = 
   (a^2 - 4*b)^(1/2)/2 - a/2
 - a/2 - (a^2 - 4*b)^(1/2)/2

The desired output, however, which allows a and b to be arrays, is

a = 
   (a.^2 - 4*b).^(1/2)/2 - a/2
 - a/2 - (a.^2 - 4*b).^(1/2)/2

Solution

  • solve('x^2 + a*x + b == 0') returns a 2x1 sym. I understand you want to evaluate the solution for various a and b values. To do this, you first need to convert your sym to a function using matlabFunction.

    s = solve('x^2 + a*x + b == 0');
    f = matlabFunction(s);
    

    Now f is a function of two input arguments a and b. Try it on two vectors of three a and b values:

    f([1 2 3],[1 1 1])
    

    and you will get a 2x3 array of the solutions.

    You can also use subs to achieve what you want to do:

    subs(s,{'a' 'b'},{[1 2 3 ] [1 1 1]})
    

    will substitute [1 2 3] for a and [1 1 1 ] for b and return a 2x3 sym. If you want to evaluate it, just use eval:

    eval(subs(s,{'a' 'b'},{[1 2 3 ] [1 1 1]}))