How to convert string "26/7" into a double variable?

I've tried str2double("26/7"), however it gave NaN as output.
Thanks in advance.

Respuestas (3)

Stephen23
Stephen23 el 4 de Abr. de 2020
Editada: Stephen23 el 4 de Abr. de 2020
>> str = '26/7';
>> vec = sscanf(str,'%f/%f');
>> vec(1)./vec(2)
ans = 3.7143
One line (but I would not recommend using this):
>> prod(sscanf(str,'%f/%f').^[1;-1])
ans = 3.7143
John D'Errico
John D'Errico el 4 de Abr. de 2020
Editada: John D'Errico el 4 de Abr. de 2020
Whilst I am one of the people who tends to equate eval with evil...
str = '22/7';
eval(str)
ans =
3.14285714285714
Sometimes it can come to the rescue. Eval has a Dr. Jekyll and Mr Hyde thing about it though, so beware the dark side. ;-)

6 comentarios

I am glad I know about Dr Jekyll and Mr Hyde :) Otherwise it would be a huge what the heck moment :D
Thanks for the answer, I didn't know MATLAB had an eval() function.
Note that str2num would be slightly safer. It is just a wrapper for eval so has the same issues but, at least, it tries to protect you from the most obvious dangers:
>> str2num('22/7')
ans =
3.14285714285714
@Guillaume cool, this outputs a double, right?
Guillaume
Guillaume el 4 de Abr. de 2020
Yes
John D'Errico
John D'Errico el 4 de Abr. de 2020
Editada: John D'Errico el 4 de Abr. de 2020
Yes. str2num is an option too. But then I could not have called it evil quite as easily. :)
And yes, the Jekyll and Hyde remark was something I wondered if others would catch.
Not unlike putting a reference to a slide rule in an answer these days. Most people today would look at a slide rule with a blank stare, wondering what anyone would do with it.
I did cherish my slide rule. They are mainly relegated to the antique shops now, in a sense a loss. :{
As well as being insecure eval is also slower than sscanf and rdivide, e.g. 1e5 iterations:
Elapsed time is 1.088572 seconds. % SSCAF and RDIVIDE
Elapsed time is 5.502366 seconds. % evil EVAL
KALYAN ACHARJYA
KALYAN ACHARJYA el 4 de Abr. de 2020
Editada: KALYAN ACHARJYA el 4 de Abr. de 2020
X = str2double(str) converts the text in str to double precision values.
Text is "22/7" This is not a number right "/" . What do you expect at the output?
Same case:
>> X = str2double('22+7')
X =
NaN
But if we add then
>> X = str2double('29')
X =
29

1 comentario

So, isn't there any way to evaluate the value of "22/7" first and then store as a double?

La pregunta está cerrada.

Etiquetas

Preguntada:

el 4 de Abr. de 2020

Cerrada:

el 20 de Ag. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by