필터 지우기
필터 지우기

Using fscanf to capture a mixed data string.

조회 수: 9 (최근 30일)
David Leather
David Leather 2015년 7월 28일
편집: dpb 2015년 7월 29일
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
dpb 2015년 7월 28일
편집: dpb 2015년 7월 28일
How do you want the two pieces to be joined? Give an actual example with desired result...
Oh, or do you want the full string representation as a character array or cellstring array?
David Leather
David Leather 2015년 7월 28일
I want the final result to be an nx1 array where each line is
#########-10-K-########
#########-10-K-########
essentially I want to go through every line of my text file, and see if it is a member of another array, and match the data.

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

채택된 답변

dpb
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
David Leather
David Leather 2015년 7월 28일
Thanks! I will try this later. One concern I do have is that the first string of numbers (enclosed in **) * ######### *-10-K-########, can vary from 6-9 characters in length.
dpb
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 CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by