For example I have a logial vector in MATLAB:
idx1 = [0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0]
And I want to get numbers (count each block) of such blocks: 1 1 1
, i.e. such block contain N elements == 1 (N "1"). idx1 - array, and his dimension can be any, for example 3820000.
How count many blocks (sequences of ones) occur in the entire array idx1
?
counts_idx = 0;
init_counts_idx = 0;
arr = 0;
for i = 1:length(idx1) -1
for kk = 1 : length(idx1) - 1
if idx1(kk 1) == 1
init_counts_idx = init_counts_idx 1;
arr = init_counts_idx;
else
init_counts_idx = counts_idx;
end
C = {i,arr};
end
end
I try to using cells...
CodePudding user response:
bwconncomp(idx1).NumObjects
See bwconncomp()
CodePudding user response:
You can calculate the start and end indices of each block by diff([0 idx1 0])
. Then, use this information to calculate block lengths Ns
. Finally express the result as a cell array using the function C = mat2cell(A,rowDist)
.
idx1 = [0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0];
diffs = diff([0 idx1 0]);
% find start index of the blocks
loc = find(diffs == 1);
% calc block lengths by subtracting end - start indices
Ns = find(diffs == -1) - loc;
C = mat2cell([loc' Ns'],ones(size(loc)))
4×1 cell array
{[ 4 3]}
{[ 9 3]}
{[16 6]}
{[29 3]}
If you are interested only in the number of such blocks, length(loc)
will give you the answer, it is similar to bwconncomp(idx1).NumObjects
.