Creating sub-vectors with equal entries

15 views (last 30 days)
Joshua Carr
Joshua Carr on 12 Feb 2021
Answered: darova on 13 Feb 2021
Hi all, for a homework assignment I'm given an arbitrary array that contains 1's and 0's. (numeric array not logical). I'm not allowed to use the find fuction. I'm supposed to return a vector with number of consecutive zeros, so for:
x = [0 1 0 0 0 1 0 1 1 1 0 0 0 1 0 1 1 0 0];
we would get the output y = [1 3 1 3 1 2].
What I want to know is if I could split x into subvectors for every zero, If I change the matrix x to x1 by x1 = +(~x). then I can take the sums of the individual subvectors and put them into an array giving me the output vector I want. here's a more visible example:
Given: x = [0 1 0 0 0 1 0 1 1 1 0 0 0 1 0 1 1 0 0];
Step 1, Invert x; x1 = +(~x)
x1 = [1 0 1 1 1 0 1 0 0 0 1 1 1 0 1 0 0 1 1];
Step 2, Break up vector x1 into subvectors
[1 0]
[1 1 1 0]
[1 0]
[0]
[0]
[1 1 1 0]
[1 0]
[0]
[1 1]
Step 3, sum all of the subvectors
1
3
1
0
0
3
1
0
2
Step 4, eliminate the zeros and reshape into vector
[1 3 1 3 1 2]
Any and all help appreciated. Thanks

Answers (1)

darova
darova on 13 Feb 2021
Use for loop
x = ~x;
j = 0;
k = 0;
n = sum(diff(~x)); % number of series '0'
ix = zeros(ix,1);
for i = 1:length(x)-1
j = j + 1;
if x(i)==0 && x(i+1)==1
k = k + 1;
ix(k) = j;
j = 0;
end
end

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Tags

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!