Remove last row from csv using csvread
10 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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.
However, if you're using a recent release of Matlab, consider using readtable() instead of csvread().
12 个评论
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 Center 和 File Exchange 中查找有关 Large Files and Big Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!