How do I analyze certain data usIng for loop?

Hey everyone!
The following code picks out certain data files. In matlab I have the files stored in numerical order. How do I modify my code so it not only chooses the files defined by my if statement, but the files directly after them?
Thank you!
fn = fieldnames(MCR_full.MIB037.Reaches);
allPeaks = cell(20,1);
prominencePeaks = zeros([],[]);
for k = 1:20
kins = MCR_full.MIB037.Reaches.(fn{k}).kin;
t = kins(:, 1);
y = kins(:, 3);
peaks = findpeaks(y);
reachLimitArray = find(peaks >= 0.1);
allPeaks{k} = reachLimitArray;
if length(reachLimitArray) > 1
disp ('There is at least two value above the limit.')
f=figure(k);
hold on;
for i = 1:length(reachLimitArray)
index = reachLimitArray(i);
prominencePeaks(k,i) = peaks(index);
end
end
end

Answers (1)

Hi Mackenzie,
As per my understanding to select the files directly after the ones defined by the if statement, an additional loop can be added that iterates over the next files. The loop "for j = k+1:min(k+1, 20)" iterates over the next files (j) starting from the file after the current one "(k+1)". The "min(k+1, 20)" ensures that the loop doesn't go beyond the last file. Please refer to the code below for reference:
fn = fieldnames(MCR_full.MIB037.Reaches);
allPeaks = cell(20,1);
prominencePeaks = zeros([],[]);
for k = 1:20
kins = MCR_full.MIB037.Reaches.(fn{k}).kin;
t = kins(:, 1);
y = kins(:, 3);
peaks = findpeaks(y);
reachLimitArray = find(peaks >= 0.1);
allPeaks{k} = reachLimitArray;
if length(reachLimitArray) > 1
disp('There is at least two value above the limit.')
f = figure(k);
hold on;
for i = 1:length(reachLimitArray)
index = reachLimitArray(i);
prominencePeaks(k,i) = peaks(index);
end
% Loop over the next files
for j = k+1:min(k+1, 20)
kins_next = MCR_full.MIB037.Reaches.(fn{j}).kin;
y_next = kins_next(:, 3);
peaks_next = findpeaks(y_next);
reachLimitArray_next = find(peaks_next >= 0.1);
if ~isempty(reachLimitArray_next)
% Process the files directly after the current one
% Add your code here to handle the next files
end
end
end
end
Hope this helps!
Regards,
Maneet Bagga

Asked:

on 13 Jan 2022

Answered:

on 25 Sep 2023

Community Treasure Hunt

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

Start Hunting!