# How to convert strings to symbolic expressions?

33 views (last 30 days)
Renjie Xiong on 21 Nov 2020
Commented: Renjie Xiong on 24 Nov 2020
Here is a function I defined:
function [X]=Taylor(a,b,h,p,m)
n=(b-a)/h;
X=zeros(1,n+1);
X(1)=p;
A=sym(zeros(1,m));
syms t;
f=str2sym('t+x(t)^2');
A(1)=f;
df=f;
for i=2:m
df0=diff(df,t);
df=subs(df0,'diff(x(t),t)','t+x(t)^2');
A(i)=df;
end
A=subs(A,'x(t)','y');
for i=1:n
B=A;
B=subs(B,'y',X(i));
B=subs(B,'t',a+(i-1)*h);
C=zeros(1,m+1);
for k=1:m
C(k+1)=B(k)*h^k/factorial(k);
C(1)=C(1)+C(k+1);
end
X(i+1)=X(i)+C(1);
end
end
When I tried to use this function, however, I got an error message. Here is the error message:
>> [X]=Taylor(a,b,h,p,m)
Error using sym>convertChar (line 1537)
Character vectors and strings in the first argument can only specify a variable or number. To evaluate character vectors and strings representing symbolic expressions, use 'str2sym'.
S = convertChar(x);
Error in sym (line 220)
Error in sym/subs>inputchk (line 249)
(length(sym(x))~=1 || length(sym(y))~=1) && isvarname(char(x))
error(inputchk(X,Y));
Error in sym/subs (line 145)
Error in Taylor (line 17)
df=subs(df0,'diff(x(t),t)','t+x(t)^2');
In line 17, I tried everything to fix this error, but none of them works. I guess I should convert my string expression to symbolic expression somewhere, but I don't know how to do. Please, can anyone help me? Thank you so much!
Stephen23 on 24 Nov 2020
" I guess I should convert my string expression to symbolic expression somewhere, but I don't know how to do."
The list "Create Symbolic Variables, Expressions, and Functions" here:
contains a link to this function:
Did you try it?

Shubham Rawat on 24 Nov 2020
Hi Renjie Xiong,
You are right the error which is thrown is due to the string, so you may change the string to symbolic expression by this,
df = subs(df0, str2sym('diff(x(t),t)'), str2sym('t+x(t)^2'));
Renjie Xiong on 24 Nov 2020
It works! Thank you so much!