addition loops in matlab
Show older comments
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 Comments
Austin Decker
on 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
on 12 Feb 2022
Austin Decker
on 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));
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!