Remove last row from csv using csvread

조회 수: 15 (최근 30일)
Ted Baker
Ted Baker 2020년 4월 19일
댓글: Adam Danz 2020년 4월 19일
Hi, I have the following code to read all the csv files in a directory.
close all;
csvfiles = dir('*.csv');
for file = csvfiles'
datafromfile = csvread(file.name, 17, 0);
freq = datafromfile(:,1);
power = datafromfile(:,2);
end
However, the csv files contain a cell with END in the last cell, as follows. This results in an error when the script runs.
HEADER HEADER HEADER
HEADER HEADER HEADER
29950250 3.46649905459066 0 0 0
30000000 5.23598452822347 0 0 0
END
How can I remove the last element/row from the csv so the script runs?
EDIT: I've included an example csv file.

채택된 답변

Adam Danz
Adam Danz 2020년 4월 19일
편집: Adam Danz 2020년 4월 19일
If you must use csvread() and you know the rows and columns of the file that should be read, use the following syntax to limit the section of the file that is read into Matlab.
M = csvread(filename,R1,C1,[R1 C1 R2 C2]) r
However, if you're using a recent release of Matlab, consider using readtable() instead of csvread().
  댓글 수: 12
Ted Baker
Ted Baker 2020년 4월 19일
Apologies, I had a brain fart moment. For reference my final code is:
close all;
csvfiles = dir('*.csv');
for file = csvfiles'
filelines = strtrim(strsplit(fileread(file.name), newline()));
startstop = find(ismember(upper(filelines), {'BEGIN','END'})) - [0,2];
T = csvread(file.name, startstop(1), 0, [startstop(1) 0 startstop(2) 4]);
freq = T(:,1);
power = T(:,2);
end
Massive thank you Adam.
Adam Danz
Adam Danz 2020년 4월 19일
"I see the data is stored in cells as a comma-delimited string. "
That's true of some of the lines but not all of them.
filelines(1) % not true
ans =
1×1 cell array
{'! FILETYPE CSV'}
filelines(200) % true
ans =
1×1 cell array
{'1137500081.75,10.3549267889657,0,0,0'}
"Is there a quick way of putting the first and second elements of this into variables "
That's what the csvread is doing. To isolate only col 1 and only col 2
freq = csvread('FILE1_.csv', 17, 0, [17 0 417 0]); % col 1
pow = csvread('FILE1_.csv', 17, 1, [17 1 417 1]); % col 2
Although tables are usually a way to keep data organized.
T = csvread('FILE1_.csv', 17, 0, [17 0 417 1]);
Tbl = array2table(T,'VariableNames',{'freq','pow'})
head(Tbl) % Check out the first few rows
Technically you could do it directly from the filelines cell array but it's messy.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by