Irregular intervals inside a for loop
Afficher commentaires plus anciens
Hello, I'm trying to work out how to do two actions (lets call them A and B), where action A is repeated n amount of times after which action B is repeated m amount of times, with n and m being integers.
this all takes place in a for loop with say, index p.
Essentially what I want as my output when n = 2 and m = 3 is:
Action A
Action A
Action B
Action B
Action B
Action A
Action A
...etc.
I tried doing the following:
n=5
for p = 1:100
q = floor(p/n);
if rem(q,2) == 0
disp('Action A')
else
disp('Action B')
end
end
But ofcourse, this only works for regular intervals (I'm quite a nooby in MATLAB so excuse me if this is a weird way to approach this)
Réponses (3)
n = 2;
m = 3;
z = n+m;
for p = 1:20
if ismember(mod(p,z),1:n)
disp('Action A');
else
disp('Action B');
end
end
4 commentaires
Kerr Beeldens
le 23 Mar 2022
Voss
le 23 Mar 2022
You're welcome!
Be aware that there is a functional difference between this answer and the other answer, which is how many times any action (Action A or Action B) will occur on each iteration of the "p" loop. In the method used in this answer, one action occurs each time; in the method used in the other answer, n+m actions occur each time.
Kerr Beeldens
le 23 Mar 2022
Voss
le 23 Mar 2022
Whatever works works! I just wanted you to be aware of the difference.
David Hill
le 23 Mar 2022
for p=1:100
for a=1:n
%Action A
end
for b=1:m
%Action B
end
end
3 commentaires
Kerr Beeldens
le 23 Mar 2022
Image Analyst
le 23 Mar 2022
@Kerr Beeldens it does work nicely. And it does what you said in a simpler and more straightforward method than messing with floor() and rem() like you tried to do.
Kerr Beeldens
le 23 Mar 2022
John D'Errico
le 23 Mar 2022
Modifié(e) : John D'Errico
le 23 Mar 2022
There are multiple ways to do this. For example:
P = primes(20); % Note that P is a ROW vector
P
SumP = 0;
for P_i = P
SumP = SumP + P_i;
end
SumP
Do you see there is effectively no index at all? The loop variable is the corresponding element of P.
Or, I might have done this:
Q = (1:5).^2
ProdQ = 1;
for ind = 1:numel(Q)
Q_ind = Q(ind);
ProdQ = ProdQ*Q_ind;
end
ProdQ
In the latter case, I used a uniform index in the form of ind, but then immediately index into the non-uniform vector Q.
Next, we can have a loop on characters.
S = 'The Quick Brown Fox jumped over the lazy dog';
words = split(S).'
Again, note that words is again a ROW vector. Now the for loop can access the elements of this row vector.
for W = words
disp(W{:})
end
Be careful, as that trick fails when the vector is a column vector.
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!