weird behaviour of textscan

2 views (last 30 days)
Yosef
Yosef on 9 Mar 2012
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?

Answers (1)

Friedrich
Friedrich on 9 Mar 2012
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 Comments
Yosef
Yosef on 9 Mar 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 on 9 Mar 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

Sign in to comment.

Categories

Find more on Data Import and Export in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!