Remove last row from csv using csvread

15 visualizaciones (últimos 30 días)
Ted Baker
Ted Baker el 19 de Abr. de 2020
Comentada: Adam Danz el 19 de Abr. de 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.

Respuesta aceptada

Adam Danz
Adam Danz el 19 de Abr. de 2020
Editada: Adam Danz el 19 de Abr. de 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 comentarios
Ted Baker
Ted Baker el 19 de Abr. de 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 el 19 de Abr. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by