Hello !
I have an problem to which I'd like to find an efficient solution.
Let the vector :
[0, x, x, x, x, 0, x, x, x, 0, x, x, x, x, x]
where x is an unkown integer.
I'd like to extract the first 3 x's starting from each '0'
So I thought about indexing the '0's which gives me something like :
[1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0]
And then use this index to extract groups of value around the '1's
or generate from the previous index another one taking into account the first three 'x's :
[1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0]
But it seems that there is no easy way to do that.
Is there an indexing syntax or a function that would allow me to do that ?
Thank you for your time ~

 採用された回答

Stephen23
Stephen23 2020 年 8 月 17 日

1 投票

>> V = [0, 11, 12, 13, 14, 0, 21, 22, 23, 0, 31, 32, 33, 34, 35];
>> X = logical(conv([1,1,1,1],+(V==0)));
>> Z = V(X(1:numel(V)))
Z =
0 11 12 13 0 21 22 23 0 31 32 33

2 件のコメント

Martin de Lagarde
Martin de Lagarde 2020 年 8 月 17 日
Thanks a lot, it did the trick for me !
Bruno Luong
Bruno Luong 2020 年 8 月 17 日
Just be careful when applying for cases where there is less than 3 non-zeros between 2 zeros, many succesive zeros exist.

サインインしてコメントする。

その他の回答 (2 件)

Bruno Luong
Bruno Luong 2020 年 8 月 17 日
編集済み: Bruno Luong 2020 年 8 月 17 日

1 投票

% Test array
A=randi([0 5],1,20)
d=diff([A(:)==0; true]);
idx0=find(d==-1);
idx1=find(d==1);
if length(idx1)>length(idx0)
idx1(1)=[];
end
lgt=min(idx1-idx0,3); % 3 elements max
lgt=reshape(lgt,size(idx0)); % for empty 0x1 special case
C=arrayfun(@(i,k) A(i+(0:k)), idx0, lgt, 'unif', 0);
B=cat(2,C{:})
KSSV
KSSV 2020 年 8 月 17 日

0 投票

How about this?
A = rand(15,1) ;
A(1)= 0 ;
A(6) = 0 ;
A(10) = 0 ;
idx = A==0 ;
idy = 1+cumsum(idx);
idz = 1:length(A);
C = accumarray(idy(~idx),idz(~idx),[],@(r){A(r)});
celldisp(C)

1 件のコメント

Martin de Lagarde
Martin de Lagarde 2020 年 8 月 17 日
Wow hat's a really good start !
But perhaps I wasn't clear in my question but I dont want to split in groups between my idx, I want to get rid of the values following the third (for example) value after my idx.
So if I have let's say
0, 1, 2, 3, 4, 5, 0, 5, 4, 3, 2, 1, 0, 1, 3, 4, 2, 5, 0, 5, 3, 4, 2, 1
I'd like to keep in one vector
0, 1, 2, 3, 0, 5, 4, 3, 0, 1, 3, 4, 0, 5, 3, 4
So I can use the code you've provided but I need to cut the end of the cells in the cell array from the 4th value and then put then back in a unique vector.
Thanks a lot for your answer !

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by