Pick values around an index
Afficher commentaires plus anciens
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 ~
Réponse acceptée
Plus de réponses (2)
Bruno Luong
le 17 Août 2020
Modifié(e) : Bruno Luong
le 17 Août 2020
% 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
le 17 Août 2020
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 commentaire
Martin de Lagarde
le 17 Août 2020
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!