How do I read strings with textscan?
조회 수: 16 (최근 30일)
이전 댓글 표시
I have the following format I'm trying to read from a file with textscan:
10000 'name1 name2 name3 ..' 3 4 5 6 7 8 9 10 11
20000 'name4 name5 ..' 3 4 5 6 7 8 9 10 11
30000 'name6 name7 name8 name9 ..' 3 4 5 6 7 8 9 10 11
repeat format for 150 lines
The issue is I want everything between single quotes to be read/stored as one string. The problem is that there are whitespaces and also sometimes there are 3 names, sometimes there are 2, sometimes 4.
I've tried:
formatSpec = '%d %s %f %f %f %f %f %f %f %f %f'
C = textscan(fid,formatSpec,150)
I know my formatSpec is too basic for strings with multiple whitespaces and words. Can you help with how I should read in this format? I basically want C to be an 150x11 cell matrix where column 2 is the entire string from single quote to single quote.
Thanks!
댓글 수: 0
답변 (2개)
Walter Roberson
2018년 2월 21일
The trick to this is to use a format item
''%[^'']''
for each place you want one of those quoted strings.
But there is a different approach: use fileread to read the entire file into a string, and then replace all ' in the string with " and then textscan the string with a %q format element. (That is, you can pass a string as the first parameter to textscan instead of a file identifier)
댓글 수: 0
C.J. Harris
2018년 2월 21일
Have you tried specifying the delimiter?
formatSpec = '%d %s %f %f %f %f %f %f %f %f %f';
C = textscan(fid,formatSpec,150, 'Delimiter', '''');
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!