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 ~

 Akzeptierte Antwort

Stephen23
Stephen23 am 17 Aug. 2020

1 Stimme

>> 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 Kommentare

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Bruno Luong
Bruno Luong am 17 Aug. 2020
Bearbeitet: Bruno Luong am 17 Aug. 2020

1 Stimme

% 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 am 17 Aug. 2020

0 Stimmen

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 Kommentar

Martin de Lagarde
Martin de Lagarde am 17 Aug. 2020
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 !

Melden Sie sich an, um zu kommentieren.

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by