1

I want to import a csv file (data.csv) which is structured as follows

Area,MTU,Biomass MW,Lignite MW
CTA|DE(50Hertz),"01.01.2015 00:00 - 01.01.2015 00:15 (CET)","1227","6485"
CTA|DE(50Hertz),"01.01.2015 00:15 - 01.01.2015 00:30 (CET)","","6421"
CTA|DE(50Hertz),"01.01.2015 00:30 - 01.01.2015 00:45 (CET)","1230","n/e"
CTA|DE(50Hertz),"01.01.2015 00:45 - 01.01.2015 01:00 (CET)","N/A","6299"

I've tried to use textscan which works pretty well, but the process stops once the empty quotation marks are reached. The argument 'EmptyValue',0 does not work.

file = fopen('data.csv');
data = textscan(file, '%q %q "%f" "%f"', 'Delimiter', ',',...
    'headerlines', 1,'TreatAsEmpty', {'N/A', 'n/e'}, 'EmptyValue',0);
fclose(file);

Any idea, on how to import the whole file.

John
  • 5,735
  • 3
  • 46
  • 62
max.mustermann
  • 127
  • 1
  • 1
  • 9

1 Answers1

1
textscan(file,'%q%q%q%q%[^\n\r]','Delimiter',',','headerlines',1);

worked just fine for me. You get values like: "01.01.2015 00:00 - 01.01.2015 00:15 (CET)" But those are trivial to write a separate parser for. Don't try to do it all in one step. That will cause you much pain and suffering. Break it up into simple single steps.

Also, I highly recommend right clicking your file in the "Current Folder" window in matlab, then selecting "Import Data" This makes importing CSV (or tab separated, or fixed width data files) trivial.

John
  • 5,735
  • 3
  • 46
  • 62
  • Why `%[^\n\r]`? What ist the benefit? – max.mustermann Jan 28 '16 at 16:15
  • That's what the Import Data tool added. But, I suspect it matches everything on the line that doesn't match the first part. Thus, (for example) extra spaces, or spurious fields don't hose the parsing. – John Jan 28 '16 at 17:13