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)
C1 = 1×5 cell array
{[42.5300]} {'A'} {'B'} {[1]} {'C'}
pos1 = 19
[C2, pos2] = textscan(m2, pattern, 'Delimiter', delimiter)
C2 = 1×5 cell array
{[42.5300]} {'A'} {','} {[1]} {'C'}
pos2 = 18
[C3, pos3] = textscan(m3, pattern, 'Delimiter', delimiter)
C3 = 1×5 cell array
{[42.5300]} {'A'} {'B'} {[1]} {0×1 char}
pos3 = 18
[C4, pos4] = textscan(m4, pattern, 'Delimiter', delimiter)
C4 = 1×5 cell array
{[42.5300]} {','} {'1'} {0×1 double} {0×1 char}
pos4 = 16

댓글 수: 1

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))
s1 = 1×5 cell array
{[42.5300]} {'A'} {'B'} {'1'} {'C'}
s2 = cleanStrFcn(strsplit(m2,',','CollapseDelimiters',false))
s2 = 1×5 cell array
{[42.5300]} {'A'} {0×0 char} {'1'} {'C'}
s3 = cleanStrFcn(strsplit(m3,',','CollapseDelimiters',false))
s3 = 1×5 cell array
{[42.5300]} {'A'} {'B'} {'1'} {0×0 char}
s4 = cleanStrFcn(strsplit(m4,',','CollapseDelimiters',false))
s4 = 1×5 cell array
{[42.5300]} {0×0 char} {0×0 char} {'1'} {'C'}

댓글을 달려면 로그인하십시오.

 채택된 답변

Jeremy Hughes
Jeremy Hughes 2021년 11월 18일

1 개 추천

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

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')
str =
'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{:}
ans = 4×1
42.5300 42.5300 42.5300 42.5300
ans = 4×1 cell array
{'A' } {'A' } {'A' } {0×0 char}
ans = 4×1 cell array
{'B' } {0×0 char} {'B' } {0×0 char}
ans = 4×1
1 1 1 1
ans = 4×1 cell array
{'C' } {'C' } {0×0 char} {'C' }
Joan Vazquez
Joan Vazquez 2021년 11월 22일
Thanks Jeremy and thanks Stephen for the examples

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

제품

릴리스

R2021b

태그

질문:

2021년 11월 18일

댓글:

2021년 11월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by