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?

답변 (1개)

Friedrich
Friedrich 2012년 3월 9일

0 개 추천

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

Yosef
Yosef 2012년 3월 9일
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 2012년 3월 9일
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

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Data Import and Export에 대해 자세히 알아보기

제품

질문:

2012년 3월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by