How to use textscan with empty char fields
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Joan Vazquez
am 18 Nov. 2021
Kommentiert: Joan Vazquez
am 22 Nov. 2021
How can I use textscan with files that include these kind of lines, with empty chars?
m1 = 'HELLO,42.53,A,B,1,C'; % Only this works fine
m2 = 'HELLO,42.53,A,,1,C';
m3 = 'HELLO,42.53,A,B,1,';
m4 = 'HELLO,42.53,,,1,C';
pattern = 'HELLO%f%c%c%f%c';
delimiter = ',';
[C1, pos1] = textscan(m1, pattern, 'Delimiter', delimiter)
[C2, pos2] = textscan(m2, pattern, 'Delimiter', delimiter)
[C3, pos3] = textscan(m3, pattern, 'Delimiter', delimiter)
[C4, pos4] = textscan(m4, pattern, 'Delimiter', delimiter)
1 Kommentar
Adam Danz
am 18 Nov. 2021
Since this doesn't answer the question, How can I use textscan ..., I'll leave a comment rather than an answer.
A workaround is to use strsplit and then some post-processing to convert chars to numbers.
m1 = 'HELLO,42.53,A,B,1,C';
m2 = 'HELLO,42.53,A,,1,C';
m3 = 'HELLO,42.53,A,B,1,';
m4 = 'HELLO,42.53,,,1,C';
cleanStrFcn = @(s)[str2double(s{2}),s(3:end)];
s1 = cleanStrFcn(strsplit(m1,',','CollapseDelimiters',false))
s2 = cleanStrFcn(strsplit(m2,',','CollapseDelimiters',false))
s3 = cleanStrFcn(strsplit(m3,',','CollapseDelimiters',false))
s4 = cleanStrFcn(strsplit(m4,',','CollapseDelimiters',false))
Akzeptierte Antwort
Jeremy Hughes
am 18 Nov. 2021
The format specifier %c always reads one character, no matter what that character is. What you likely want it %s, which reads all the characters up to the next matching delimiter.
2 Kommentare
Stephen23
am 18 Nov. 2021
str = sprintf('%s\n', 'HELLO,42.53,A,B,1,C', 'HELLO,42.53,A,,1,C', 'HELLO,42.53,A,B,1,', 'HELLO,42.53,,,1,C')
out = textscan(str, 'HELLO,%f%s%s%f%s', 'Delimiter',',');
out{:}
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Text Files finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!