查找二进制数组连续的数
我想找到全系列的1和0的长度在MATLAB一个逻辑阵列。这就是我所做的:
I want to find the lengths of all series of ones and zeros in a logical array in MATLAB. This is what I did:
A = logical([0 0 0 1 1 1 1 0 1 1 0 0 0 0 0 0 1 1 1 1 1]);
%// Find series of ones:
csA = cumsum(A);
csOnes = csA(diff([A 0]) == -1);
seriesOnes = [csOnes(1) diff(csOnes)];
%// Find series of zeros (same way, using ~A)
csNegA = sumsum(~A);
csZeros = csNegA(diff([~A 0]) == -1);
seriesZeros = [csZeros(1) diff(csZeros)];
这工作的,并给出了 seriesOnes = [4 2 5]
和 seriesZeros = [3 1 6]
。然而,在我看来是相当丑陋。
This works, and gives seriesOnes = [4 2 5]
and seriesZeros = [3 1 6]
. However it is rather ugly in my opinion.
我想知道是否有更好的方法来做到这一点。性能是不是一个问题,因为这是廉价的( A
比几千元素不再)。我找了code的清晰度和优雅。
I want to know if there is a better way to do this. Performance is not an issue as this is inexpensive (A
is no longer than a few thousand elements). I am looking for code clarity and elegance.
如果没有更好的可以做,我只是把这个在一个小帮手功能,所以我没有看它。
If nothing better can be done, I'll just put this in a little helper function so I don't have to look at it.
您可以使用现有的code代表的运行长度编码的,它执行(丑陋的),为您的工作和然后筛选出你自己的向量。这样,您的辅助函数是相当普遍和其功能从名称 runLengthEn code
。
You could use an existing code for run-length-encoding, which does the (ugly) work for you and then filter out your vectors yourself. This way your helper function is rather general and its functionality is evident from the name runLengthEncode
.
重用code href=\"http://stackoverflow.com/a/18490872/3139711\">这个答案:
Reusing code from this answer:
function [lengths, values] = runLengthEncode(data)
startPos = find(diff([data(1)-1, data]));
lengths = diff([startPos, numel(data)+1]);
values = data(startPos);
您会然后用过滤掉你的载体:
You would then filter out your vectors using:
A = logical([0 0 0 1 1 1 1 0 1 1 0 0 0 0 0 0 1 1 1 1 1]);
[lengths, values] = runLengthEncode(A);
seriesOnes = lengths(values==1);
seriesZeros = lengths(values==0);