MATLAB: How to extract sections of data from a csv file

importing excel dataMATLAB

I am having difficulty extracting the data I require from a csv file. I have been provided with a csv file which has the outputs of a number of simulations. However I have hit a dead-end on how to extract the data without doing it individually, i.e. opening in the import window and selecting the range of cells I wish to import by altering the range selected and doing this for each simulation. The format of the csv is attached, the output comes in the form of a table where one simulation is produced with the given headings along the top and the simulated results in the columns below. The next simulation is then produced below in the same form. Ideally I would want to input all the data directly into vectors, e.g. the year data into an 11×10 vector, with each column holding the relevant data for each simulation, i.e the first column of the vector holding A3:A13, the second column holding A17:A27 and so on. Any advice on how to extract the data would be greatly appreciated. Thanks in advance.

Best Answer

d=[]; % initialize an array for the data
fmt=repmat('%f',1,14); % format string to match file
fid=fopen('filename');
for i=1:10
d=[d;cell2mat(textscan(fid,fmt,12,'headerlines',2, ...
'collectoutput',1 ...
'delimiter',','))]; % read each section;concatenate
fgetl(fid) % had to do this to get synchronized again...find it often
end
fid=fclose(fid);
The above returns the data in one array; if you instead want each simulation separately, instead of the concatenation above use a cell array to store each read section--
ERRATUM
fmt=[repmat('%f',1,14) '\n']; % format string to match line of file data
fid=fopen('filename');
for i=1:10 % repeat for all sections in file
d(i)=textscan(fid,fmt,12,'headerlines',2, ...
'collectoutput',1 ...
'delimiter',',')]; % read each section into cell array
end
fid=fclose(fid);
NB: The \n (newline) in the format string solves the position in the file it seems. I guess it's one of those cases where it's probably technically wrong without it but the scanning routines skip over it transparently in the vectorized portion but not when the scan is started over. Again, "why" is indecipherable as far as I can tell, it "just is".