How do I create a nested for loop to find consecutive numbers in a matrix? See example below.

2 ビュー (過去 30 日間)
Steven Gangano
Steven Gangano 2022 年 4 月 29 日
回答済み: Matt J 2022 年 4 月 29 日
A = [0 1 0 0 1 0 0
1 0 0 0 0 1 0
1 0 0 1 0 1 1
1 1 0 0 1 1 0
1 1 1 0 1 1 0
1 1 0 0 1 1 0 ];
1)
This is a 6x7 matrix. I wanted to check each row to see if it finds [0 0 0 0] and then if it finds it, then store it into a vector.
Can this be done with a nested for loop?
The way I wanted it to check for [0 0 0 0] for each row is as follows:
Row 1: A(1, 1:4), A(1,2:5), A(1,3:6), A(1,4:7)
Row 2: A(2, 1:4), A(2,2:5), A(2,3:6), A(2,4:7)
Row 3: A(3, 1:4), A(3,2:5), A(3,3:6), A(3,4:7)
etc...up until row 6.
2)
Also can this done for each column using for loops also? Check if it finds [1 1 1 1]' in each column?
Column 1: A(1:4, 1), A(2:5,1), A(3:6,1)
Column 2: A(1:4, 2), A(2:5,2), A(3:6,2)
etc...up until column 7
OR
Is there any easier method not using any fancy built in functions and just using for loops and if/else conditionals?

回答 (1 件)

Matt J
Matt J 2022 年 4 月 29 日
A = [0 1 0 0 1 0 0
1 0 0 0 0 1 0
1 0 0 1 0 1 1
1 1 0 0 1 1 0
1 1 1 0 1 1 0
1 1 0 0 1 1 0 ];
k=ones(1,4);
rows= find( any( conv2(~A,k,'valid')==4 ,2) ) %containing [0,0,0,0]
rows = 2
columns= find(any( conv2(A,k','valid')==4 ,1) ) %containing [1;1;1;1]
columns = 1×2
1 6

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by