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

3 visualizaciones (últimos 30 días)
Tian
Tian el 7 de En. de 2017
Comentada: Tian el 7 de En. de 2017
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!

Respuesta aceptada

Stephen23
Stephen23 el 7 de En. de 2017
Editada: Stephen23 el 7 de En. de 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.

Más respuestas (1)

Walter Roberson
Walter Roberson el 7 de En. de 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

Categorías

Más información sobre Data Import and Export en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by