Creating sub-vectors with equal entries

7 ビュー (過去 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 Center および File ExchangeMultidimensional Arrays についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by