addition loops in matlab
Afficher commentaires plus anciens
assume i have a vector array:
a=[1 1 1 0 0 1 1 1]
how can i put loop such that if sum of any three successive elements is equal to 3, it prints 'ali'.
can it be done without loops?
3 commentaires
Austin Decker
le 12 Fév 2022
I'd have to think about a loop-less answer, but one way to get what you want is:
a = [1,1,1,0,0,1,1,1];
for i = 1:length(a)-2
tmp = sum(a(i:i+2));
if tmp == 3
disp("ali");
end
end
ali hassan
le 12 Fév 2022
Austin Decker
le 12 Fév 2022
Well, MATLAB is likely looping behind the scenes, but you could do this:
a = [1,1,1,0,0 1,1,1];
ind1 = 1:length(a) -2;
ind2 = ind1 + 2;
result = arrayfun(@(x,y) sum(a(x:y)),ind1,ind2);
qty = sum(result == 3);
disp(join(repmat("ali",qty,1),newline));
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements 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!