Remove last row from csv using csvread

14 Ansichten (letzte 30 Tage)
Ted Baker
Ted Baker am 19 Apr. 2020
Kommentiert: Adam Danz am 19 Apr. 2020
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.

Akzeptierte Antwort

Adam Danz
Adam Danz am 19 Apr. 2020
Bearbeitet: Adam Danz am 19 Apr. 2020
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 Kommentare
Ted Baker
Ted Baker am 19 Apr. 2020
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 am 19 Apr. 2020
"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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by