String ' 1 45789', can I use textscan to get 1, 45, and 789 ?

3 views (last 30 days)
Hello everyone. I got a file and it contains many numbers, like str=' 98 99 99100101102'. Every number occupy 3 digits, so I want 98,99,99,100,101,102. However, using textscan(str,'%3d',6),I can only get 98,99,991,1,11,2. So, how to realize 98,99,99,100,101,102? Thank you very much!

Accepted Answer

Stephen23
Stephen23 on 7 Jan 2017
Edited: Stephen23 on 7 Jan 2017
A simple and robust method:
>> str2double(num2cell(reshape(' 98 99 99100101102',3,[])',2))
ans =
98
99
99
100
101
102
Or less preferable (because it calls eval):
>> str2num(reshape(' 98 99 99100101102',3,[])')
ans =
98
99
99
100
101
102
And of course you can read the file data as strings:
>> C = textscan(' 98 99 99100101102','%3c','whitespace','');
>> C{1}
ans =
98
99
99
100
101
102
and then use either of the methods as above to convert to numeric.

More Answers (1)

Walter Roberson
Walter Roberson on 7 Jan 2017
Unfortunately you cannot use textscan for fixed width numeric fields that have spaces. Each time textscan encounters a numeric field (or even a string field) specification, it skips all leading characters that are part of the configured Whitespace option, and only then does it start the width count. You cannot get around the problem by setting Whitespace to empty because the numeric conversion operator fail if the field begins with whitespace.
If I recall correctly, R2016b introduced the possibility of fixed width numeric fields to be handled by readtable, but other than that you need to use one of the techniques Stephen shows

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!