How to read specific numbers (colums) of a csv file

14 views (last 30 days)
Neko Benítez
Neko Benítez on 5 Oct 2019
Answered: Jeremy Hughes on 7 Oct 2019
I have a csv file with the next format:
  • The first row is a row of strings separated by commas, which indicates the name of each column
  • The next rows are a combination of strings and numeric data.
Here you have a brief description. I just put the first 3 rows, but the rows varies from file to file, so it is unknown.
I need to extract from that set of data, just the columns "time" and "power1" without the header, which would be like columns 3 and 4. I tried this:
data = csvread('test.csv',1,2)
With that code, I avoid to read the first row and start the reading from the second colum, so I also avoid the string "5". The problem is that I get always this error:
Error using dlmread (line 147)
Mismatch between file and format character vector.
Trouble reading 'Numeric' field from file (row number 1, field number 17) ==> ""device1"""\n
Error in csvread (line 48)
m=dlmread(filename, ',', r, c);
I read the documentation and it seem you can delimiter the range putting and additional array in csvread, something like this:
data = csvread('test.csv',1,2,[R1 C1 R2 C2])
The problem is that it does not work. I tried with different combinations, trying to find out how it works but always the same error.
The final result I want to obtain would be something like this, a matrix called 'data' with two colums (time and power) and all the information in files
data =[ 1570147201 237
1570147203 430
1570147203 247
I see this like a simple operation, I checked on internet but I can not do it. I attach a file with the origina data. Can anyone help, please?

Answers (2)

Ugur Acar
Ugur Acar on 5 Oct 2019

Why dont you read all data instead of just column number 2 and 4, then continue your code just by reading what ever data is needed

  1 Comment
Neko Benítez
Neko Benítez on 7 Oct 2019
How can I do that? Could you give me an brief example please? I thought that csvread just read the file, but it does not work with my example.

Sign in to comment.

Jeremy Hughes
Jeremy Hughes on 7 Oct 2019
I'd do this:
opts = detectImportOptions(filename);
opts.SelectedVariableNames = opts.VariableNames([3 4]);
T = readtable(filename,opts)



Community Treasure Hunt

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

Start Hunting!

Translated by