Having difficulty reading in a file with csvread()

2 Ansichten (letzte 30 Tage)
Stewart Charles
Stewart Charles am 12 Mär. 2014
Bearbeitet: dpb am 25 Mär. 2014
Hi All,
I have a text file which looks like this:
Date,Col1,Col2
2012/06/06 11:40:12,1.01849,1.01881
2012/06/06 11:40:13,1.0185,1.01881
etc
I want to read this into a matrix like this:
[2012 06 06 11 40 12 1.01849 1.01881;
2012 06 06 11 40 12 1.01850 1.01881
etc
]
I can't seem to do this with csvread or textscan.
Any ideas?

Akzeptierte Antwort

dpb
dpb am 12 Mär. 2014
csvread can't because it's not comma-delimited all fields so that's a non-starter
Air code--
fmt='%d/d/d d:d:d,%f,%f';
d=cell2mat(textscan(fid,fmt,'headerlines',1,'delimiter',''));
Caveat: As said, untested and while I think the 'delimiter','' and explicit delimiter matching will work, the C input parsing often throws a curveball. Anyway, that's where I'd start.

Weitere Antworten (2)

Stewart Charles
Stewart Charles am 25 Mär. 2014
Excellent. Thanks for your help. The actual code turned out to be:
c = textscan(fid, '%d/%d/%d %d:%d:%d,%f,%f','HeaderLines',1,'Delimiter',' ');
d = cell2mat(c(1:6));
v = cell2mat(c(7:8));
Note: I added some % and also found that you can't have ints and floats in the one matrix.
Thanks again!
  1 Kommentar
dpb
dpb am 25 Mär. 2014
Bearbeitet: dpb am 25 Mär. 2014
Yeah, don't know why didn't get all the % signs in there--I guess 'cuz I'm a Fortran guy at heart and detest the C format strings, maybe... :)
I guess I hadn't ever noticed that problem before -- but it's simple enough to work around as one doesn't have to use %d for the integer values...
>> type stew.txt
Date,Col1,Col2
2012/06/06 11:40:12,1.01849,1.01881
2012/06/06 11:40:13,1.0185,1.01881
>> d=cell2mat(textscan(fid,'%f/%f/%f %f:%f:%f,%f, %f', ...
'headerlines',1,'collectoutput',1));
>> num2str(d,'%.4f')
ans =
2012.0000 6.0000 6.0000 11.0000 40.0000 12.0000 1.0185 1.0188
2012.0000 6.0000 6.0000 11.0000 40.0000 13.0000 1.0185 1.0188
>>

Melden Sie sich an, um zu kommentieren.


Image Analyst
Image Analyst am 25 Mär. 2014
Wow. Complicated. Hopefully you have R2013b or later because by far the easiest way is to just simply create a table with readtable():
t = readtable('test.dat')

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by