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!