我在Matlab中有一个基本问题。我需要输入一个二进制信号并输出一个二维数组,其中第一列是顺序出现的次数,第二列是它的值。
例如:
>> arr = [0;0;0;1;1;1;0];
>> tokenizeSignal(arr)
ans =
3 0
3 1
1 0
连续三个0,然后连续三个1,然后一个0.
答案 0 :(得分:2)
您想要的是游程编码。这是一种方法:
ind = [true; diff(arr)~=0]; % logical index of values that start runs
len = diff([find(ind); numel(arr)+1]); % run lengths
result = [len arr(ind)]; % build result
答案 1 :(得分:0)
这是一种实现此目的的简单方法:
% input
arr = [0;0;0;1;1;1;0];
% make sure the input is a column vector (else the concatenation
% to create index won't work)
arr = arr(:);
% create an index that is 1 for the first group of equal values,
% 2 for the second group, etc.
index = 1 + cumsum([0 ; logical(diff(arr))]);
% use grpstats to determine how many of each index there are and
% what the unique value associated with that index is; using
% 'min' to determine unique value is fine since all the elements
% in a given group are equal
[count, value] = grpstats(arr, index, {'numel', 'min'});
% display the answer
disp([count, value])
3 0
3 1
1 0