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 件のコメント

Austin Decker
Austin Decker 2022 年 2 月 12 日
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
ali hassan 2022 年 2 月 12 日
thanks a lot. i had the same in my mind. but i cant figure out for loop less answer.
Austin Decker
Austin Decker 2022 年 2 月 12 日
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));

サインインしてコメントする。

 採用された回答

DGM
DGM 2022 年 2 月 12 日
編集済み: DGM 2022 年 2 月 12 日

0 投票

This works easily enough. After R2016a, you can do the same with movsum().
a = [1 1 1 0 0 1 1 1];
if any(conv(a,[1 1 1],'valid')==3)
fprintf('ali\n')
end
ali

4 件のコメント

ali hassan
ali hassan 2022 年 2 月 12 日
@DGM what can be other possible ways?
DGM
DGM 2022 年 2 月 12 日
Any sort of convolution or sliding window filter tool that implements some linear combination of elements. You could use conv(), imfilter() nlfilter(), movmean(), movsum(). I'm sure there are others.
ali hassan
ali hassan 2022 年 2 月 12 日
編集済み: ali hassan 2022 年 2 月 12 日
thanks a lot @DGM. adding a bit twist here.
a = [1 nan 1 1 0 0 nan 1 1 nan 1];
suppose it contains nan as well. how can i do the same and ignore nan?
if i use movsum, nan will be removed but the entry will still be considered. how can i also make it to ignore nan entry as well?
DGM
DGM 2022 年 2 月 12 日
編集済み: DGM 2022 年 2 月 12 日
To omit nans:
a = [2 nan 1 1 0 0 nan 1 1 nan 1];
% using movsum
s = movsum(a,3,'omitnan');
any(s(2:end-1)==3)
ans = logical
1
% using conv
a(isnan(a)) = 0;
s = conv(a,[1 1 1],'valid');
any(s==3)
ans = logical
1
If the value range of a never extends beyond [0 1], then you could also simply treat any propagated NaNs as 0. This is simply because it wouldn't be possible to have a sum equal to 3 if the window size were also 3 and any element were anything other than 1.
a = [1 nan 1 1 0 0 nan 1 1 nan 1];
s = conv(a,[1 1 1],'valid') % this will pass NaN
s = 1×9
NaN NaN 2 1 NaN NaN NaN NaN NaN
any(s==3) % NaNs aren't equal to 3
ans = logical
0

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2022 年 2 月 12 日

編集済み:

DGM
2022 年 2 月 12 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by