Pick values around an index
Mostrar comentarios más antiguos
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 ~
Respuesta aceptada
Más respuestas (2)
Bruno Luong
el 17 de Ag. de 2020
Editada: Bruno Luong
el 17 de Ag. de 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
el 17 de Ag. de 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 comentario
Martin de Lagarde
el 17 de Ag. de 2020
Categorías
Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!