Need help explaining what my for loop is doing when reading in .dat files
Show older comments
I'm trying to learn and apply a for loop to call in multiple .dat files so that I can then plot them. I have a folder (myFolder) which has multiple days of 3 different types of data, so I specifically grab only the "Es" data files for each day. I searched a bunch of answers on here and finally found one that worked for me but it involves this extra step at the bottom collating all the data "allDataArray". If the "Append data" section is not in the code then "dataArray" seems to only give the last day of data in the folder and won't plot each day, even though it does read them all in. Can someone please explain why the "dataArray" is only showing the last day of data and explain how I can put a plotting line into the for loop itself, currently I have it running after with the "allDataArray" but I'd like to run it without the "Append data" section.
% Specify the folder where the files live.
myFolder = 'C:\Users\tbrob\OneDrive\SO298 (2023)\Data\MATLAB\WorkingFiles';
% 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, '*Es*.dat'); % The folder has 3 different files types I only want the Es data from each day.
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 = readtable(fullFileName);
dataArray=table2array(dataArray);
% Append data
if k == 1
allDataArray = dataArray;
else
allDataArray = [allDataArray; dataArray]; % Must have same number of columns
end
end
%The allDataArray has rows with NaN values and then the variable names at
%the beggining of each day, which we dont want so just getting rid of them via the NaNs
rows = any(isnan(allDataArray),2);
allDataArray(rows,:) = [];
%plotting
x=(320:2:950);
y=allDataArray(:,7:322);
L=y(1:2:end,:);
R=y(2:2:end,:);
subplot(2,1,1);
plot(x,L);
subplot(2,1,2);
plot(x,R);
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing 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!