0
votes

I have been exploring the Matlab symbolic toolbox, in preparation for an upcoming final. However, I seem not to be able to convert a string inputted from the user to a symbolic expression, and then use it for integration.

a = input('Plese enter a = ');
b = input('Please enter b = ');
function1 = input('Please enter the function: ', 's');

syms x eq1 
eq1 = sym(function1);

Integral1 = int(eq1 , x, a, b);
Simpson = 1 / 6 * (b - a) * (subs(eq1 , x, a) + 4 * ...
    (subs(eq1 , x, (a+b)/2))...
    + subs(eq1 , x, b));

fprintf('The value of the integral is %s \n', Integral1);
fprtinf('The aprroximation with simp is %s \n', Simpson);

Simpson is the integral approximation from simpson's rule. The error I get is something along the lines of "Conversion to 'sym' returned the MuPAD error: Error: unexpected 'identifier'" the line number would be the line

eq1 = sym(function1);
2

2 Answers

0
votes

One way to do this is using eval:

function1 = input('Please enter the function: ', 's');
eq1=eval(function1);

But you need to convert the results to doubles before you can display them with fprintf:

fprintf(''The value of the integral is %s \n', double(Integral1));
0
votes

Starting R2017b, use str2sym

>> syms f(x)
>> function1 = input('Please enter the function: ', 's');
Please enter the function: sin(x)
>> f(x) = str2sym(function1)
f(x) =
sin(x)

See: https://www.mathworks.com/help/symbolic/str2sym.html