addition loops in matlab
Ältere Kommentare anzeigen
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 Kommentare
Austin Decker
am 12 Feb. 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
am 12 Feb. 2022
Austin Decker
am 12 Feb. 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));
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!