MATLAB: String ‘ 1 45789’, can I use textscan to get 1, 45, and 789

textscan

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!

Best Answer

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.