Length consecutive value 1 within a 2D matrix

Having a 2 dimensional array, e.g.
[ 0, 0, 0,1,1,1,2 ;
0,0,1,1,1,1,2;
0,1,1,1,1,1,0;
0,0,0,1,1,0,0]
I want for each row the length of consecutive 1
In this case R1 = 3, R2= 4, R3=5,R4=2.

1 件のコメント

Jan
Jan 2022 年 3 月 19 日
Are several runs possible as in [0,1,1,0,1,1]?

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

 採用された回答

Image Analyst
Image Analyst 2022 年 3 月 19 日

1 投票

Try this: I've made it general and put the results into a cell array in case some row has more than one region of 1's, like it might have 2 or 5 or 20 runs of 1's.
m = [ 0, 0, 0,1,1,1,2 ;
0,0,1,1,1,1,2;
0,1,1,1,1,1,0;
0,0,0,1,1,0,0;
1,1,0,1,1,1,0] % Last row has 2 contiguous regions instead of 1.
mb = m == 1
[rows, columns] = size(mb);
for row = 1 : rows
% Make measurements of all lines of 1's.
props = regionprops(mb(row, :), 'Area');
% Extract all the lengths into a vector and then put into a cell.
R{row} = [props.Area];
end
R % Shows in command window
R =
1×5 cell array
{[3]} {[4]} {[5]} {[2]} {[2 3]}
If you know in advance that there is just one run of 1's per row then you can use just a regular (non-cell array) vector:
m = [ 0, 0, 0,1,1,1,2 ;
0,0,1,1,1,1,2;
0,1,1,1,1,1,0;
0,0,0,1,1,0,0] % Last row has 2 contiguous regions instead of 1.
mb = m == 1
[rows, columns] = size(mb);
for row = 1 : rows
% Make measurements of all lines of 1's.
props = regionprops(mb(row, :), 'Area');
% Extract all the lengths into a vector and then put into a cell.
R(row) = [props.Area];
end
R
Shows
R =
3 4 5 2

1 件のコメント

Odo Luo
Odo Luo 2022 年 3 月 23 日
Thank you , this helped me a lot !!

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

その他の回答 (0 件)

カテゴリ

製品

リリース

R2021a

タグ

質問済み:

2022 年 3 月 19 日

コメント済み:

2022 年 3 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by