How to create a dynamic array, by counting the content of my current array?

조회 수: 3 (최근 30일)
eirini
eirini 2015년 12월 10일
답변: amal laabidi 2021년 5월 8일
Hi Matlab friends,
I have an array: A=[1,1,0,0,0,0,1,1,1,0,0,0,1,1]
and I want to create to other (dynamic) arrays, where I will count how many continuous'1' and '0' I have. So, I want to create the new arrays: For '1': B=[2,3,2] For '0': C=[4,3]
Do you know how can I do it?
I would really appreciate your answer!!
Regards, Eirini

답변 (2개)

arich82
arich82 2015년 12월 10일
This is a variation on run length encoding.
Note that find(diff(A)) returns the index of the end of each phase (where a phase is a run of zeros or ones); also note that the last element in A will always be the end of a phase, as well as the element '0' (i.e. the element before A(1)).
Taking the diff of these indices tells you the length of each phase. Putting it all together:
rl = diff([0, find(diff(A)), numel(A)]); % run lengths
B = rl(1:2:end);
C = rl(2:2:end);
Note that whether B corresponds to 1 or 0 depends on A(1); you could either write an if statement to assign B and C accordingly, or do something more obfuscated to assign them automagically.
Please accept this answer if it helps, or let me know in the comments if I've missed something.
  댓글 수: 1
arich82
arich82 2015년 12월 10일
For completeness:
2 - A(1) returns 2 if A(1) == 0, and 1 if A(1) == 1|.
Conversely, 1 + A(1) returns 2 if A(1) == 1, and 1 if A(1) == 0.
Therefore, the following code automatically assigns the runlengths of ones to B, and zeros to C:
rl = diff([0, find(diff(A)), numel(A)]); % run lengths
B = rl((2-A(1)):2:end); % rl's of ones
C = rl((1+A(1)):2:end); % rl's of zeros

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


amal laabidi
amal laabidi 2021년 5월 8일
How to create a dynamic table, to store values measured using a mpu6050 sensor in matlab?
I transfer the measured data using a mpu6050 sensor to the matlab to display it, how to create a table to sotcker this data?

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by