Extracting particular rows and column from bunch of excel files and saving into one file

Hi,
I have bunch of excel files in the folder with a lot of data in them, only data is useful to me is in columnn 3 of each file. First row of each file is the header and I do not want to include the header in the extracted data so I want 3 column from each file and 2:1002 data in rows from every single file and after extraction want to save it in different csv file so I can further analyse the data. Trying since morning but still sucks to come up with the proper script. Need help!
Code tried so far:
folder = fullfile('C:','Users','muhammad','Desktop','Velocity');
files = dir( fullfile(folder, '*.csv') );
for ii = 1:length(files)
data = csvread(fullfile(folder,files(ii)));
res=youranalysisfunction(data([2:1002]:3));
end
Error:
Error using fullfile (line 67)
All inputs must be strings, character vectors, or cell arrays of character vectors.
Error in ExtractColumns (line 8)
data = csvread(fullfile(folder,files(ii)));

 Accepted Answer

files(ii) is a struct. You need to access the name property
data = csvread(fullfile(files(ii).folder,files(ii).name))
Also, on newer versions, it is better to use readmatrix(), you can skip the header line directly
folder = fullfile('C:','Users','muhammad','Desktop','Velocity');
files = dir( fullfile(folder, '*.csv') );
for ii = 1:length(files)
data = readmatrix(fullfile(files(ii).folder,files(ii).name), 'NumHeaderLines', 1)
res=youranalysisfunction(data(:,3));
end

5 Comments

I am still getting an error!
Unrecognized function or variable 'youranalysisfunction'.
Error in ExtractColumns (line 9)
res=youranalysisfunction(data(:,3));
This is a user-defined function. If you got the code from someone else and you don't know what it does, then you can simply remove it
folder = fullfile('C:','Users','muhammad','Desktop','Velocity');
files = dir( fullfile(folder, '*.csv') );
for ii = 1:length(files)
data = readmatrix(fullfile(files(ii).folder,files(ii).name), 'NumHeaderLines', 1)
res = data(:,3);
end
Hi,
I ran the code. there are 15 csv files in the folder
where this line below only extracting 9 columns there should be 15 column extracted
data = readmatrix(fullfile(files(ii).folder,files(ii).name), 'NumHeaderLines', 1)
and this line only giving me 1 column at the end
res=data(:,3);
Please see the screenshot attached!
I am not sure why it is reading 9 instead of 15 columns. Can you attach a file?
"this line only giving me 1 column at the end"
You mentioned in your question that you only want 3rd column.
Please see the attached!
3rd column from each file!
so i have csv files with alot of data in it and all i want to extract the 3rd column from each file and collect them all togheter in a separate csv file and save it.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!