convert string to double

7 vues (au cours des 30 derniers jours)
Christelle Requena
Christelle Requena le 12 Déc 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 commentaire
Jos (10584)
Jos (10584) le 12 Déc 2017
What do you expect to get? Do you want to evaluate the formula?

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 12 Déc 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() !!

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by