How do I create a for loop with mutiple conditions in MATLAB?
10 views (last 30 days)
Show older comments
Hi, I am a super rookie who really don't know much about MATLAB. However, my supervisor required me to rewrite a script to fit for our current study. I tried but I am not so sure how to do it, may I ask for some advice, please?
% calculate Stim accuracy
for a = 1:4 % total no. of conditions
StimACCC = mean(StimACC(Cond == a & Subject == i));
T3(:, a) = StimACCC; % save data
It works to generate the data that I need, however, in the second script that I am writing for there are multiple conditions, Cond (3) and Congruency (2).
I tried to write like below:
% calculate StimACC accuracy
for a = 1:3% total no. of conditions for Conditions
if Congruency > 0
StimACCC = mean(StimACC(CueCond == a & Congruency == 0 & Subject == i));
else
StimACCC = mean(StimACC(CueCond == a & Congruency == 1 & Subject == i));
T3(:, a) = StimACCC; % save data
It doesn't work and generate data as [0.979166666666667 1 NaN], however, after mixing Cond (3) and Congruency (2), there should be 6 data generated for each participant.
I don't know where the problem is and how to fix it. May I ask for some advice, please?
0 Comments
Accepted Answer
Ram Sreekar
on 29 Jun 2023
Hi Karen,
As per my understanding, you want to generate a total of 6 outputs for each participant, depending on different values of the two variables Cond(3 values) and Congruency(2 values).
But according to your code, the result is being calculated depending on whether ‘Congruency’> 0 or not, for every ‘a’. So, only one result is generated for each value of ‘a’.
If you want to generate 6 different outputs for all combinations of values ‘Cond’ and ‘Congruency’, you can do it by using a nested for loop. You can refer to the example code given below.
% Create T3 with NaNs to store the 6 outputs
T3 = NaN(6, 1);
% index for T3
index = 1;
% calculate StimACC accuracy
for a = 1:3 % total no. of conditions for CueCond
for b = 0:1 % total no. of conditions for Congruency
StimACCC = mean(StimACC(CueCond == a & Congruency == b & Subject == i));
T3(index) = StimACCC;
index = index + 1;
end
end
Hope this helps you resolve your query.
More Answers (1)
Sulaymon Eshkabilov
on 29 Jun 2023
1st of all, if you need to create if .. else .. end statement to compare scalars or signle value variables, for .. end loop is not necessary. If you want to check individual value of a vector or matrix within if .. else .. end condition, that is a different story.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!