Creating sub-vectors with equal entries

조회 수: 12 (최근 30일)
Joshua Carr
Joshua Carr 2021년 2월 12일
답변: darova 2021년 2월 13일
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