Clear Filters
Clear Filters

How to import a particular text file and plot.

2 views (last 30 days)
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?

Accepted Answer

Matt Tearle
Matt Tearle on 21 Sep 2012
Edited: Matt Tearle on 21 Sep 2012
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.

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!