read csv in matlab

In Matlab, there are several ways to read a CSV (Comma Separated Values) file. Here's one example:

main.m
filename = 'mydata.csv';
delimiter = ',';
startRow = 2;

% Read columns of data as strings:
formatSpec = '%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%f%f%s%s%s%f%f%s%s%s%s%f%f%s%s%s%f%s%f%s%s%s%f%s%s%s%s%f%s%s%s%s%f%s%f%s%f%s%f%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%f%s%s%s%s%s%s%f%s%s%s%s%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s%s%s%s%s%f%s%s%s';
data = readtable(filename, 'Delimiter', delimiter, 'HeaderLines', startRow-1, 'Format', formatSpec);

% Convert strings to appropriate data types:
data.Var16 = str2double(strrep(data.Var16, ',', '.'));
data.Var17 = str2double(strrep(data.Var17, ',', '.'));
data.Var20 = str2double(strrep(data.Var20, ',', '.'));
data.Var22 = str2double(strrep(data.Var22, ',', '.'));

% Display first 10 rows of the data:
disp(data(1:10,:));
1580 chars
17 lines

In this example, we start by defining the input file name, delimiter, and starting row (which defaults to row 1 if not specified). Then, we specify the format of the data in the file, which in this case has 96 columns, some of which are strings and some of which are numeric.

The readtable function reads the data into a Matlab table object, which makes it easy to manipulate and analyze the data. Finally, we use str2double to convert some of the string columns to numeric types, and we replace commas with dots as the decimal separator (this step may be unnecessary depending on the locale settings of your computer).

By default, the readtable function assumes that the first row of the CSV file contains variable names, which are used as column headers for the table. If your file doesn't have column headers, you can add the 'ReadVariableNames', false option to the readtable function.

gistlibby LogSnag