How to convert strings to symbolic expressions?

25 次查看(过去 30 天)
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'.
Error in sym>tomupad (line 1253)
S = convertChar(x);
Error in sym (line 220)
S.s = tomupad(x);
Error in sym/subs>inputchk (line 249)
(length(sym(x))~=1 || length(sym(y))~=1) && isvarname(char(x))
Error in sym/subs>mupadsubs (line 154)
error(inputchk(X,Y));
Error in sym/subs (line 145)
G = mupadsubs(F,X,Y);
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!
  1 个评论
Stephen23
Stephen23 2020-11-24
" 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
Shubham Rawat 2020-11-24
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'));

更多回答(0 个)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by