필터 지우기
필터 지우기

Count amount of 0's and 1's in an array

조회 수: 2 (최근 30일)
Sasha Melov
Sasha Melov 2015년 4월 6일
편집: Jos (10584) 2015년 4월 7일
Hello, I'm working on a image processing project. My current task is to get the number of 0's and 1's connected elements. Example: I have an 1D array which looks like:
[0000 1111 0000000 1111 000 1 00 11111 00 11111 00]
What I want is to count elements connected to each other and return something like this:
[4 4 7 4 3 1 2 5 2 5 2]
Is there any easy way to do that? This includes generating dynamical array, so I have no idea how to do that without iterating through array twice

채택된 답변

Mahdiyar
Mahdiyar 2015년 4월 6일
Hi Melov
Please, let me know if it is what you want.
clc
clear
A = [0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 0 0 1 1 1 1 1 0 0 1 1 1 1 1 0 0];
B = A(2:end);
C = A(1:end-1) - B;
D = find(C~=0);
Result = [D(1) D(2:end) - D(1:end-1) length(A)-D(end)]
Regards,
  댓글 수: 1
Sasha Melov
Sasha Melov 2015년 4월 7일
works exactly like I wanted,thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Jan
Jan 2015년 4월 6일
A = [0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 0 0 1 1 1 1 1 0 0 1 1 1 1 1 0 0];
[B, N] = RunLength(A);
B =
0 1 0 1 0 1 0 1 0 1 0
N =
4 4 7 4 3 1 2 5 2 5 2

Jos (10584)
Jos (10584) 2015년 4월 7일
편집: Jos (10584) 2015년 4월 7일
Since the array is always an alternation of zeros and ones
N = diff([0 find(diff(A)) numel(A)])
will produce the runs of consecutive zeros and ones.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by