weird behaviour of textscan

this is weird:
>> cell2mat(textscan('5','%d'))*0.5
ans =
3
doesn't matlab supposed to know to automatically interpret integers as floats when necessary? For example:
>> sscanf('5','%d')*0.5
ans =
2.5000
Any ideas?

Respuestas (1)

Friedrich
Friedrich el 9 de Mzo. de 2012

0 votos

Hi,
I would rather say that sscanf behaves weired. The textscan does it correct:
(Integers or integer arrays and scalar double-precision floating-point numbers. This yields a result that has the same data type as the integer operands)
So textscan gives an int, cell2mat keeps it and than its an int multiplied by a double which gives an int like states in the link above
But sscanf returns a double, whereas I would hope to get an int. But this is not the case. This is also documented:
"Only numeric specifiers, A is numeric. If format includes only 64-bit signed integer specifiers, A is of class int64. Similarly, if format includes only 64-bit unsigned integer specifiers, A is of class uint64. Otherwise, A is of class double. If sizeA is inf or n, then A is a column vector. If the input contains fewer than sizeA elements, MATLAB pads A with zeros"
Since there is no ld or lu specified as format, you get a double back.
So overall everything behaves as it should.

2 comentarios

Yosef
Yosef el 9 de Mzo. de 2012
Thanks for the answer Friedrich! I guess you are right and it works as intended, but in my humble opinion this is a design flaw. This type of obvious inconsistency is a recipe for trouble. It costed me more then two hours of my time this morning.
Friedrich
Friedrich el 9 de Mzo. de 2012
I agree. I would wish that sscanf return an int instead of a double in such a situation.
So your question is answered? Please mark it as answered than.
Thanks,
Friedrich

Iniciar sesión para comentar.

Categorías

Productos

Preguntada:

el 9 de Mzo. de 2012

Community Treasure Hunt

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

Start Hunting!

Translated by