Creating sub-vectors with equal entries

2 次查看(过去 30 天)
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

回答(1 个)

darova
darova 2021-2-13
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

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by