convert string to double
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Christelle Requena
el 12 de Dic. de 2017
Respondida: Walter Roberson
el 12 de Dic. de 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 comentario
Respuesta aceptada
Walter Roberson
el 12 de Dic. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!