String ' 1 45789', can I use textscan to get 1, 45, and 789 ?
3 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Stephen23
2017-1-7
编辑:Stephen23
2017-1-7
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.
更多回答(1 个)
Walter Roberson
2017-1-7
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Export 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!