Using fscanf to capture a mixed data string.

5 次查看(过去 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
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 中查找有关 Data Type Conversion 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by