How to create an array from a 'for loop' of numeric data read from multiple excel files?

1 view (last 30 days)
  1. A list of excel files is made
  2. The numeric data is imported from multiple excel files using 'xlsread' in a for loop.
>> facdata={'1.csv','2.csv','3.csv'};
>> for fn=facdata
xlsread(fn{:},'D9:D9');
end

Answers (1)

R
R on 11 Sep 2024
Here how you can do it:
% List of Excel files
facdata = {'1.xlsx', '2.xlsx', '3.xlsx'}; % Ensure the file extension is correct
% Initialize an array to store the data
dataArray = []; % Or preallocate if you know the size
% Loop through each file and read the specified cell
for i = 1:length(facdata)
% Read the numeric data from each file
data = xlsread(facdata{i}, 'D9:D9');
% Append the data to the array
dataArray = [dataArray; data]; % Vertically concatenate
end
% Display the collected data
disp('Collected Data:');
disp(dataArray);
Note that xlsread is not recommended as of now. You should use readtable instead. To use readtable instead of xlsread, you'll need to adjust your approach since readtable reads entire tables rather than specific cells. However, you can still achieve the same goal by reading the table and then extracting the specific cell value you need. Here's how you can do it:
for i = 1:length(facdata)
% Read the entire table from the Excel file
tableData = readtable(facdata{i});
% Extract the value from cell D9
% Assuming D9 corresponds to the 9th row and 4th column in zero-indexed format
data = tableData{9, 4}; % Adjust indices if the table has headers
% Append the data to the array
dataArray = [dataArray; data]; % Vertically concatenate
end
Hope this helps.
  1 Comment
Nicholas Findanis
Nicholas Findanis on 15 Sep 2024
Edited: Nicholas Findanis on 16 Sep 2024
Thank you this information was so quick to respond and works a treat. I also found a way to concatenate CSV files using the following method.
>> facdata={'1.csv','2.csv','3.csv'};
>> for i=1:n
list(:,i)=csvread(sprintf('%d.csv',i),8,3,[8,3,8,3]);
end
Very much appreciate your help!

Sign in to comment.

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!