The number of consecutive ocurrances in an array

조회 수: 1 (최근 30일)
reham elnabawy
reham elnabawy 2017년 4월 30일
댓글: Stephen23 2017년 5월 1일
I have an array that is shown as: a=[0,0,1,1,1,0,0,1] and I would like to get the number of consecutive ocurrances in it along with the number itself meaning that I would like the output to be b=[2,0,3,1,2,0,1,1] where 0 occurred two consecutive times, 1 occurred three consecutive times, etc. Please help me and thank you in advance.
  댓글 수: 3
John Chilleri
John Chilleri 2017년 5월 1일
The b is a description of vector a:
Two 0s, then three 1s, then two 0s, then one 1.
Stephen23
Stephen23 2017년 5월 1일
@Image Analyst: run length encoding.

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

답변 (1개)

Guillaume
Guillaume 2017년 5월 1일
This is trivially achieved with diff and find:
a = [0, 0, 1, 1, 1, 0, 0, 1];
transitions = find(diff(a));
runlengths = diff([0, transitions, numel(a)]);
runvalues = a([transitions, end]);
valuelength = reshape([runlengths; runvalues], 1, [])
  댓글 수: 1
Stephen23
Stephen23 2017년 5월 1일
+1 Nice and simple. That is the way to do it.

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by