MATLAB: How to load multiple .dat files into MATLAB

dat filesimport dataimport multiple files

Hey,
I have 53 .dat (000n_3.dat, 000n_50.dat; 000n+1_3.dat, 000n+1_50.dat; etc. – as you can see, their names are similar but not purely consecutive) files all stored in the same directory, which I want to import into MATLAB all at the same time. Loading each of them works (e.g. load(0002_03.dat)) but what I want is to have all 53 of them loaded into a giant .mat spreadsheet from where I can neatly copy and paste all the rows and columns into an Excel spreadsheet.
How can I do this?
Thanks in advance.

Best Answer

You can use the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F Use the second example. Then, inside the loop, read the data file with csvread(), readtable(), importdata(), or any of several other functions and append the data to your growing array. After the loop, create a filename and call xlswrite()
% Specify the folder where the files live.
myFolder = 'C:\Users\yourUserName\Documents\My Data'; % Wherever...
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.dat'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as reading it in, plotting it, using it, or whatever.
dataArray = csvread(fullFileName); % Or whatever function you want.
% Append data
if k == 1
allDataArray = dataArray;
else
allDataArray = [allDataArray; dataArray]; % Must have same number of columns
end
end
xlswrite(outputFilename, allDataArray, 'All Data', 'A1');
Related Question