フィルターのクリア

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

1 回表示 (過去 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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by