Using fscanf to capture a mixed data string.
조회 수: 9 (최근 30일)
이전 댓글 표시
Hi,
I have a text file formatted
#########-10-K-########
#########-10-K-########
...
I want to bring the entire contents of the lines into an nx1 matrix or array, where n is the number of lines in my text file.
So far I have tried:
x=fscanf(fn, '%f-10-K-%f\n', [inf])
which creates a 2nx1 matrix where the first float is the first entry, and the second float is the second entry.
x=fscanf(fn, '%[0123456789-K\n]', [inf])
which honestly seems to have worked except for the fact that is results in a 1x67165 char array.
x=fscan(fn, '%[0123456789-K]\n', [inf])
which just results in one really long string.
I have also tried
x=fscan(fn, '%f%c%d%d%c%c%c%f\n', [inf])
which isn't working.
Any tips?
댓글 수: 2
채택된 답변
dpb
2015년 7월 28일
OK, you don't want to match the strings, then; characters in a format string other than those with specific formatting meaning are matched and ignored.
Simplest is just return a cellstring array...
data=textread('yourfile.dat','%s');
If you prefer, you can cast into a character array as
data=char(textread('yourfile.dat','%s'));
Read up in doc on difference if not fully aware.
NB: I used textread above even though it's been relegated to "redhaired stepchild" status by TMW. It reads directly from a file saving the extra fopen/fclose steps and is often more convenient than textscan. The higher-level routines will do a more convenient job of shaping the returned output to the file as they keep track of line length automagically which you have to do explicitly with fscanf
댓글 수: 2
dpb
2015년 7월 28일
편집: dpb
2015년 7월 29일
No problemo...the cellstring will be variable length per cell (with leading blanks truncated), but the character array will be padded (on the right) to the length of the longest string in the array. It's more work if the leading blanks are considered significant and must have the result right-justified internally.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!