count 1's in binary
이전 댓글 표시
Hi,
This is what i want... I have a binary array
001111000000011100000000011111
from here i have to count the number 1 in such way
result: 0,4,0,3,0,5.... how to get this?
채택된 답변
추가 답변 (3개)
Wayne King
2014년 7월 22일
Hi Sasha, I'm presuming your binary number is a character array:
s = '001111000000011100000000011111';
K1 = strfind(s,'1');
F = diff(find([1 diff(K1 - (1:length(K1)))]));
splitvec = mat2cell(K1,1,[F length(K1)-sum(F)]);
NumConsec1 = cellfun(@numel,splitvec);
NumConsec1 gives you the number of consecutive 1's. splitvec is a cell array with the actual indices of those ones, whicy you can see if you enter
splitvec{:}
댓글 수: 1
Shasha Glow
2014년 7월 22일
편집: Shasha Glow
2014년 7월 22일
What about this:
series_length=find(diff(binary_series)==-1)-find(diff(binary_series)==1);
you might have to pad binary_series with 0s at the start and end to ensure switch on and off.
댓글 수: 1
Image Analyst
2016년 12월 14일
Does not work:
% Create sample binary data.
binary_series = [0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1]
% Laslo's code below:
series_length=find(diff(binary_series)==-1)-find(diff(binary_series)==1)
Complete error message:
Matrix dimensions must agree.
Error in test3 (line 4)
series_length=find(diff(binary_series)==-1)-find(diff(binary_series)==1)
Anshuk Uppal
2018년 2월 16일
편집: Walter Roberson
2018년 2월 16일
A working tested algorithm -
n_ofErrors=flip(find(diff(error_vector)==-1))(1:1:length(find(diff(error_vector)==1))) - flip(find(diff(error_vector)==1));
댓글 수: 6
Anshuk Uppal
2018년 2월 16일
just pad the error vector with zeroes error_vector=[0 error_vector 0];
Guillaume
2018년 2월 16일
This is certainly not a working algorithm. The sequence of characters |)(| is never valid in matlab code. This will result in
Error: ()-indexing must appear last in an index expression.
Anshuk Uppal
2018년 2월 16일
The algorithm certainly does work, but not in matlab. It has been tested in an open source version-octave

Guillaume
2018년 2월 16일
Well, this is a matlab forum, not an octave forum...
Anshuk Uppal
2018년 2월 16일
You can make it work by truncating the array first and not using the whole expression in a single line. That should solve the error matlab generates. An algorithm is a series of instructions(may be mathematical) that solve a problem. Differences in syntax can occur...

Guillaume
2018년 2월 16일
Well, yes. And you can make your algorithm a lot more efficient by performing diff and find only once rather than 3 times each. I also don't understand the purpose of the flip.
transitions = find(diff([0; error_vector(:); 0]));
n_ofErrors = transitions(2:2:end) - transitions(1:2:end)
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!