How to open csv files as separate numeric matrices from a certain directory?
Show older comments
I have many csv files in a folder and I need to open all as separate numeric matrices in workspace.
1 Comment
Don't make your code slow, complex, and inefficient with dynamically named variables:
The content of a cell array (as the accepted answer shows) are already separated arrays.
Accepted Answer
More Answers (1)
Image Analyst
on 13 Feb 2022
Edited: Image Analyst
on 13 Feb 2022
See the FAQ:
% Specify the folder where the files live.
myFolder = pwd; % or 'C:\Users\yourUserName\Documents\My Pictures'; or wherever they are
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.csv'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as reading it in as an array with csvread() or readmatrix() or importdata().
data = imread(fullFileName);
end
By the way, you should process each set of data inside the loop. If you will need the data later, you can put it into a multidimensional array or a cell array.
It's a very bad idea to give each data set its own unique name. Why? See the FAQ:
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!