Calculate true in binary array specifically

1 view (last 30 days)
Hello!
I have a boolean one-dimensional array, like
binary = [0,0,0,1,0,1,0,1,1,1,0,1,1,1,0,0,0,1,1,0 ..., 0]
And I like to squeeze from this the following:
[1, 1, 3, 3, 2, ...]
So, I would like to calculate how many 1s (Trues) encounter in row. It is possible to write a loop somehow, like:
for i=1:size(array)
if B(14:i)== 1
count = count + 1;
else:
count = 0;
Result_Array.append(count) % I do not know builtin function exaclty.
end
Is it correct..? And I would like to know, if there is a standart matlab function for this purpose.
Thank you very much!

Accepted Answer

Stephen23
Stephen23 on 23 Sep 2018
Edited: Stephen23 on 23 Sep 2018
This is MATLAB, so you don't need to use loops to solve every little task:
>> V = [0,0,0,1,0,1,0,1,1,1,0,1,1,1,0,0,0,1,1,0,0];
>> D = diff([0,V,0]);
>> find(D<0)-find(D>0)
ans =
1 1 3 3 2

More Answers (0)

Community Treasure Hunt

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

Start Hunting!