Split array into chunks based on trigger values in another array
Mostrar comentarios más antiguos
Hi all
I've searched for a bit, found some related questions, but none that want to achieve exactly what i want (point me towards one that does, if you know of one):
- https://ch.mathworks.com/matlabcentral/answers/366836-split-array-into-cell-arrays-of-different-size
- https://ch.mathworks.com/matlabcentral/answers/412088-split-array-according-to-one-column-values
However, what I am looking for is to split an array A into chunks that correspond to consecutive ones (or a single one) in array B. Consider the following example:
A = (1:10)';
B = [0 1 1 1 0 0 1 0 1 1 ]';
f = @(trig, data) % my magic function
% output of f(B,A) should be the following:
>> f(B, A)
ans = { [2, 3, 4]; [7]; [9, 10] }
I've come up with a working solution, but it looks like it can be done more efficiently, or faster. Hit me with Ideas :)
function groups = f(trig, data)
% approach with splitapply
len = length(trig);
% find rising edges (diff = 1) and falling edges (diff = -1)
d = zeros(len,1);
d(2:len) = diff(trig);
% multiply with increasing numbers to generate unique keys
g = d .* ((2:len+1).');
% apply cumsum to assign same key to samples between triggers
gs = cumsum(g);
% put NaN for negative keys (after falling edges -> where trigger is 0)
% so splitapply will ignore those samples
gs(gs < 1) = NaN;
% use findgroups to generate consecutive keys
gr = findgroups(gs);
% function that returns the array in a cell
f = @(a) {a};
% let splitapply do the work
groups = splitapply(f,data,gr);
end
Cheers
Manuel
Edit: Changed Example for more clarity
4 comentarios
Just Manuel
el 11 de Feb. de 2021
Editada: Just Manuel
el 16 de Feb. de 2021
Mathieu NOE
el 11 de Feb. de 2021
hello
seems in the very beginning of your post that B = A(k) for any k fullfilling B(k) = 1
A(B>0.5) gives the same results : ans = 2 4 5 7 8 10
I don't see the constraint that the 1 must be consecutive (so one single 1 would not trigger the data capture ?)
otherwise , in the attachement you'll find example of a "trigger" function to find positive slope and negative slope crossing points defined by a threshold value
Just Manuel
el 16 de Feb. de 2021
Mathieu NOE
el 23 de Feb. de 2021
Glad it helped !
Respuestas (0)
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!