How to process files of a particular order in MATLAB?

1 view (last 30 days)
Hi
I have saved data for multiple subject's, multiple sessions with the following name format: Sub1_S1_Epochs,Sub1_S2_Epochs, Sub2_S1_Epochs,Sub2_S2_Epochs,...
I want to load the files for each subject's 2 sessions and process that, I have written the following code, but i don't know how to process the code for each session's data before moving on to next subject.?.
Subject = {'Sub 01','Sub 02'};
Session = {'S1','S2'};
for i = 1:size(Subject,2)
for ii = 1:size(Session,2)
matFileName = sprintf('Sub%i_S%ii_Epochs.mat', i,ii);
if exist(matFileName, 'file')
matData = load(matFileName);
else
fprintf('File %s does not exist.\n', matFileName);
end
end
end
How i can load the files for both sessions and process that before moving onto next subject?
Please help.

Accepted Answer

Stephen23
Stephen23 on 8 Mar 2020
Edited: Stephen23 on 8 Mar 2020
"Possibly what is the error, it says that File doesn't exist."
Most likely the files do not exist in the location where you are trying to read them from, or the filenames are incorrect.
For example, your first example name starts with "Sub1..." but at the start of your code you have a cell array named Subjects where the first name is "Sub 01". Those are two very different name formats. No one here can tell you which one is correct. You have to know exactly what the name format is, and create names that match them exactly.
I wouldn't use a loop for the sessions, just the subjects. Perhaps something like this:
P = 'path to the folder where the files are saved'; % .e.g 'C:\MyProject\Data'
N = total number of subjects; % e.g. 3
for k = 1:N
F1 = fullfile(P,sprintf('Sub%u_S1_Epochs.mat',k));
F2 = fullfile(P,sprintf('Sub%u_S2_Epochs.mat',k));
S1 = load(F1); % LOADing into a structure is more reliable.
S2 = load(F2); % LOADing into a structure is more reliable.
% ... Do whatever with data in S1 and S2.
end

More Answers (0)

Categories

Find more on Cell Arrays 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!