Info

This question is closed. Reopen it to edit or answer.

textscan incompatible with sscanf numeric field width for seemingly complex-valued numbers

1 view (last 30 days)
Is it possible to force textscan to honour field width when handling apparently complex numbers -- as sscanf does?
>> sscanf('001i', '%3d%1c')
ans =
1
105
where 15 is double('i')
>> textscan('001i', '%3u%1c')
ans =
[0 + 1i] [0x1 char]
The only workaround I found is to import as text:
>> textscan('001i', '%3c%1c')
ans =
'001' 'i'
then calling str2double on the first string.
The character 'i' is not constant (it goes for 'a', 'b', etc.).
ADDENDUM: the single character at the end needs to be saved, it cannot be skipped or discarded as as literal.
Thanks, -FGN.

Answers (1)

dpb
dpb on 14 Jan 2017
Edited: dpb on 14 Jan 2017
Looks like another bug to me where textscan doesn't follow the rules. I'd submit it as one; im(ns)ho one should always expect consistency with the same format string between the various parsers; otherwise it's impossible to code a priori if there is no real definition.
Even worse, you can't ignore the 'i' by conventional means--
>> textscan('001i', '%di')
ans =
[0 + 1i]
>>
Depending upon what you desire for output you could possibly get by with
>> textscan('001i', '%[^i]d')
ans =
{1x1 cell}
>> ans{:}
ans =
'001'
>>
which isn't width-dependent as is the counted-width workaround above if that is an issue.
ADDENDUM
I just saw the last issue that 'i' isn't always the same character--the first option above is of no value then and I suppose also then the character itself is significant. In that case the above also fails for it as the general solution would can all alphabetic characters in $[^abc...]
ADDENDUM 2
While I still think it's a bug in textscan that should be reported, how about
>> textscan(regexprep('001i','[a-z]',',$&'),'%d,%c')
ans =
[1] 'i'
>>
as a workaround?? Essentially your kind of solution but buried in the parsing a little more deeply. (PS: think this is the first regular expression I've managed to ever get to work... :) )
  1 Comment
Felipe
Felipe on 14 Jan 2017
Thanks for your comment. I didn't know we could use regexp-like sentences -- [^i] -- in the format specification. I forgot to mention that I need to save that single character for later, so I can't completely ignore it. Thanks once again.

Tags

Community Treasure Hunt

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

Start Hunting!