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

조회 수: 2 (최근 30일)
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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by