convert string to double
7 次查看(过去 30 天)
显示 更早的评论
If I have a string like : `A = cos(2*pi*f1*t) + 4*sin(2*pi*f2*t)`
How I can convert it to double ?
I tried
B = str2num(A) % I obtain an empty matrix
or
B = str2double(A) % I obtain a Nan response...
How can I fixe it ?
1 个评论
采纳的回答
Walter Roberson
2017-12-12
MATLAB 5.1 and later, no special toolboxes:
S = 'A = cos(2*pi*f1*t) + 4*sin(2*pi*f2*t)';
temp = vectorize(regexp(S, '(?<==\s*)\S.*', 'match', 'once'));
vars = symvar(temp);
F = str2func(['@(', strjoin(vars,','), ') ', temp ]);
Now execute the function handle F, passing in the variables named in vars, in order, which in this case would be f1, f2, t.
But I suspect this is not the answer you are looking for. An answer closer to what you are looking for would be:
R2017b and later with Symbolic Toolbox
S = 'A = cos(2*pi*f1*t) + 4*sin(2*pi*f2*t)';
temp = regexp(S, '(?<==\s*)\S.*', 'match', 'once');
tempsym = str2sym(temp);
A = double( subs(tempsym) );
R2017a and earlier with Symbolic Toolbox
S = 'A = cos(2*pi*f1*t) + 4*sin(2*pi*f2*t)';
temp = regexp(S, '(?<==\s*)\S.*', 'match', 'once');
tempsym = sym(temp); %will probably give a warning message
A = double( subs(tempsym) );
But I suspect those are not the answers you are looking for either.
The answer I suspect you are looking for is:
S = 'A = cos(2*pi*f1*t) + 4*sin(2*pi*f2*t)';
eval(S);
%the result will be in A
We recommend against using eval() !!
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!