convert string to double
7 views (last 30 days)
Show older comments
Christelle Requena
on 12 Dec 2017
Answered: Walter Roberson
on 12 Dec 2017
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 Comment
Accepted Answer
Walter Roberson
on 12 Dec 2017
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 Comments
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!