count 1's in binary
Ältere Kommentare anzeigen
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?
Akzeptierte Antwort
Weitere Antworten (3)
Wayne King
am 22 Jul. 2014
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 Kommentar
Shasha Glow
am 22 Jul. 2014
Bearbeitet: Shasha Glow
am 22 Jul. 2014
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 Kommentar
Image Analyst
am 14 Dez. 2016
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
am 16 Feb. 2018
Bearbeitet: Walter Roberson
am 16 Feb. 2018
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 Kommentare
Anshuk Uppal
am 16 Feb. 2018
just pad the error vector with zeroes error_vector=[0 error_vector 0];
Guillaume
am 16 Feb. 2018
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
am 16 Feb. 2018
The algorithm certainly does work, but not in matlab. It has been tested in an open source version-octave

Guillaume
am 16 Feb. 2018
Well, this is a matlab forum, not an octave forum...
Anshuk Uppal
am 16 Feb. 2018
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
am 16 Feb. 2018
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)
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!