MATLAB Answers

0

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

Neko Benítez 님이 질문을 제출함. 5 Oct 2019
최근 활동 Jeremy Hughes 님이 답변함. 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.
id,"nodeid","time","power1","apparentPower1","powerFactor1","q1","irms1","power2","apparentPower2","powerFactor2","q2","irms2","power1pluspower2","vrms","t1","devicename"
1,"5",1570147201,237.0,472.0,0.5,407.0,1.86,48.0,177.0,0.27,170.0,0.7,285.0,253.46,29.6,"device1"
2,"5",1570147202,243.0,473.0,0.51,406.0,1.86,51.0,178.0,0.28,170.0,0.7,294.0,253.66,29.6,"device1"
3,"5",1570147203,247.0,475.0,0.51,406.0,1.87,50.0,180.0,0.27,173.0,0.71,297.0,253.99,29.6,"device1"
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?

  댓글 수: 0

로그인 to comment.

태그

제품

답변 수: 2

Ugur Acar 님의 답변 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

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.

로그인 to comment.


Jeremy Hughes 님의 답변 7 Oct 2019

I'd do this:
opts = detectImportOptions(filename);
opts.SelectedVariableNames = opts.VariableNames([3 4]);
T = readtable(filename,opts)

  댓글 수: 0

로그인 to comment.



Translated by