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 CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by