Search code examples
matlabsymbolic-math

Matlab's subs does not evaluate symbolic Bessel function


I experienced a strange behaviour in Matlab with the function subs and the built-in besselj:

syms x
f = besselj(1,x)
subs(f,1)

returns

besselj(1, 1)

even though the documentation states

"subs(s,new) returns a copy of s replacing all occurrences of the default variable in s with new, and then evaluating s.

The default variable is defined by symvar.

So I would expect the output of subs(f,1) to be 0.4401. eval(subs(f,1)) produces the correct output of 0.4401. Does anyone know why this is the case?


Solution

  • I feel like you're trying to define an anonymous function, you don't need subs or eval here, simply use f as an actual function...

    % No need to use symbolic math toolbox for x or f 
    f = @(x) besselj(1,x);  % Define f as an anonymous function of x
    f(1)                    % Evaulate f at a given point, say x = 1
    >> ans = 0.4401
    

    Side note: If for some reason you're really set on using symbolic variables (they seem overkill here) then you may just want to use the eval function and a symbolic function handle instead of subs.

    syms f(x)            % Defines f as a symfun and x as a sym variable
    f(x) = besselj(1,x); % Define the function
    eval(f(1))           % Evaluate at x=1
    >> ans = 0.4401
    

    In answer to your question about why subs doesn't "evaluate" the answer when using subs(f, 1)... It's probably because the nature of the besselj function. Because you're using symvars, you are using the symbolic math package's besselj function (as opposed to the core-package function by the same name).

    This means that a symbolic expression is displayed to the command window when subs is used, in the same way that any other symbolic expression is displayed without needing to be evaluated - i.e. they can be simplified but don't run other functions.

    This is why you then need to run eval, to evaluate the simplified symbolic expression.