How to create a dynamic array, by counting the content of my current array?
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (2)
arich82
on 10 Dec 2015
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 Comment
arich82
on 10 Dec 2015
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
on 8 May 2021
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?
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!