reading a csv file with headers and splitting that matrix into 2 matrices

82 views (last 30 days)
I am new to MATLAB. I have a .csv that is 1001 x 783. The .csv does have headers for each column and the first column is the label.
How do I read the .csv, and specific that the first row is the header. Then, turn it into a matrix. Once in matrix, I want to make 2 matrices from the original. A label matrix that is the first column of the original, and a data matrix that has the 2 column to the end, from the original matrix.
How can I do this?
So far this is what I have:
dataFile = importdata('example1.csv', headers = TRUE);
label = dataFile(1:end,1:end);
X = dataFile(2:end, 2:end)
For example: example.csv looks like this
label dog1 dog2 dog3 dog4 dog5
true 1 1 2 1 2
false 2 2 1 2 1
true 1 1 2 1 2
false 2 2 1 2 1
label matrix:
label
true
false
true
false
X matrix:
dog1 dog2 dog3 dog4 dog5
1 1 2 1 2
2 2 1 2 1
1 1 2 1 2
2 2 1 2 1

Answers (1)

Cam Jones
Cam Jones on 8 Nov 2017
Edited: Cam Jones on 8 Nov 2017
In order to import the data, I recommend using the "readtable" function which will import the data as a MATLAB table.
dataTable = readtable('example.csv');
From there, you can extract the data by indexing into the table. MATLAB uses (row,column) indexing. So to select the entire first column you can do the following:
label = dataTable(:,1);
Like wise to get the remaining columns:
X = dataTable(:,2:end);
Because the labels are string data, they would need to be converted into a cell matrix if you didn't want them in a table:
cellLabel = table2cell(label);

Categories

Find more on Cell Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!