How to import a particular text file and plot.

1 回表示 (過去 30 日間)
T
T 2012 年 9 月 21 日
Here is the data that I wish to import:
Scan(+/- seconds),Sensor1Value,Sensor2Value,Sensor3Value,Sensor4Value
-1, 2, 8, 3, 4
'#' Comment Here
9, 0, 5, 6, 7
-------------------------------------
If I want to plot this kind of data,
fid = fopen(file.txt');
% read column headers
header = textscan(fid, '%s', 5, 'delimiter', ',', ... 'commentStyle', '#');
% read numeric data
data = textscan(fid, '%f %f %f %f %f', 'delimiter', ',', ... 'commentStyle', '#');
fclose(fid);
------------
My question is, when I type in header{1} I get all five columns. Shouldn't it be the case that if I type in header{1}, header{2}, header{3},...,header{5} I should get: Scan, Sensor1Value, Sensor2Value,...,Sensor4Value respectively?

採用された回答

Matt Tearle
Matt Tearle 2012 年 9 月 21 日
編集済み: Matt Tearle 2012 年 9 月 21 日
By specifying a format string of '%s', you effectively asked textscan for a single output. But then you asked to read a string 5 times. Consequently output is a single cell which contains five things. Those five things are themselves cells, which contain the strings you want. (Confused?)
So to get the third header, do
header{1}{3}
Or, you could do
textscan(fid, '%s%s%s%s%s', 1, ...
In which case you will get back 5 cells. But then each of them contains a single cell (which contains a string)!
Unfortunately this is just the way textscan works. It makes sense for reading whole columns of data, but not so much for a header line.
You can always do what you were doing and add
header = header{1}
Or do it the other way I showed above and add
header = [header{:}]
Either way, then, header will be a 5-element cell array of the strings.
EDIT, attempting to clarify: textscan returns an n-element cell array, where n is the number of format specifiers in the format string. Each cell will contain the contents that were read from the file. If the contents were numeric, you'll just get a numeric array. But if they were strings, you'll get a cell array of strings. That's why you're ending up with cell arrays containing cell arrays.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Import and Export についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by