CircAnalyzer
CircAnalyzer

Reputation: 704

MATLAB CSV File Read

I have a CSV file with the following content:

Header line1
Space
Space
Space
,1,2,3,
1,81,82,83

And I am trying to read the data portion into a numeric matrix. Here is the code I have implemented, however I am having issues.

%To get the number of rows in the file
for i = 1:9
   headerline = fgetl(fid);
   headerline = strsplit(headerline,',')
end

fclose(fid);

fopen(fid);
% to get the data
C = textscan(fid,'%s','headerline',4,'EmptyValue',=Inf)
rowsize = size(C{1});
data = []

% to store data in matrix
for i = 1:rowsize
   data = [data, strsplit(C{1}{i},',')];
end

Can anybody recommend a better way to just read the whole file into a numeric matrix? Thanks!

Upvotes: 2

Views: 792

Answers (1)

0xMB
0xMB

Reputation: 881

All you really need is this;

fid = fopen('your.csv');
data = cell2mat(textscan(fid, '%f%f%f%f', 'Delimiter', ',', 'HeaderLines', 4));

You could also use csvread (https://www.mathworks.com/help/matlab/ref/csvread.html) if your csv just contains numeric values.

M = csvread(filename,R1,C1) reads data from the file starting at row offset R1 and column offset C1. For example, the offsets R1=0, C1=0 specify the first value in the file.

So in this case:

data = csvread('filename.csv', 4, 0)

Upvotes: 2

Related Questions