how to read a file like a table

조회 수: 1 (최근 30일)
David Pesetsky
David Pesetsky 2016년 7월 25일
댓글: dpb 2016년 7월 25일
Hello,
I'm looking to read double precision data from a file, in however many columns it is, and to the end of file. The result should be a N x M double.
i.e. if I paste this in the Matlab window, I get what I need:
table=[
1016.6 0 0 0 0 0 0 0
1016.6 0 0 0 0 0 0 0
0 -479.528 0 0 0 0 0 0
0 468.718 0 0 0 0 0 0
0 0 -385.346 0 0 0 0 0
0 0 696.118 0 0 0 0 0
0 0 0 -7591 0 0 0 0
0 0 0 7591 0 0 0 0
0 0 0 0 -7573.16 0 0 0
0 0 0 0 7573.16 0 0 0
0 0 0 0 0 -2620.704 0 0
0 0 0 0 0 4134 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 1022.074 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 7701.638
];
That gives a 16x8 double.
But in the file would be just the values, as shown.
Some form of fscan maybe, but with generalized format?
Thanks for unconfusing me...
Dave

채택된 답변

dpb
dpb 2016년 7월 25일
Use textscan without an explicit format string--that's a magic incantation that will return the data in the same shape as is in the file for regular files of all numeric data.
data=cell2mat(textscan(fid,'','collectoutput',1));
Add any additional parameters needed for delimiter, missing value, headerlines, etc., etc., ...
Or, dlmread will also return the proper shape for those files which it can handle (which generally includes those for which the above textscan "trick" will work.
Since R2013b there's readtable which will leave you with a table dataset rather than an array so whether that is/is not an advantage depends on what you're going to be doing with the data.
  댓글 수: 2
David Pesetsky
David Pesetsky 2016년 7월 25일
Thank you. I like tricks of the trade :)
dpb
dpb 2016년 7월 25일
It's undocumented for textscan; there's an example with empty string for the format string in textread still altho it's not mentioned there. I learned it functioned for textscan by accident when using the same idiom had learned from textread by habit, not by design initially.
It's a very important feature that deserves to be "shouted from the rooftop" as it ameliorates an otherwise painful problem if one doesn't know the number of elements/record plus the need for the abomination of a format string of some N repeating fields to force the proper count. In lieu of that, it's do another reshape after reading into a single column.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by