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

3 次查看(过去 30 天)
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