Spit an array when the value 0 occurs until the value 2
Mostrar comentarios más antiguos
I have an array time (6700x1) containing all numbers from -8 to 5 in ascending order.
I would like to have a new array (time_new) based on this that contains all value between 0 and 2.
I know that I can just open the array and look at which position the value 0 occurs and at wich index the value 2 and based on this do time(3981:4962). But since I'm dealing with several arrays where the position of these 2 numbers is not always the same I would like to have something more roboust that I can always use without every time open the array and look for the teo index.
Can someone help to with that?
Thanks in advance
1 comentario
Dyuman Joshi
el 29 de Jun. de 2022
Editada: Dyuman Joshi
el 29 de Jun. de 2022
Why do you think finding the position and using the index is not a robust method?
Use logical indexing then. (as @Voss has answered)
Respuesta aceptada
Más respuestas (1)
Walter Roberson
el 29 de Jun. de 2022
Your request is a bit ambiguous, so I will give two possibilities.
loc0 = find(YourArray == 0, 'first');
%use this
loc2F = find(YourArray == 2, 'first');
subsetF = YourArray(loc0:loc2F-1);
%OR use this
loc2L = find(YourArray == 2, 'last');
subsetL = YourArray(loc0:loc2L);
Now subsetF includes from the first 0 to the last value before the 2. subsetL includes from the first 0 to the last 2. You do not need both of these; I am just not clear which one you want.
Note that this code is not designed to work if there are no 0 or there are no 2.
3 comentarios
Walter Roberson
el 29 de Jun. de 2022
Also,
look_for = 0:1; %or 0:2
subset = YourArray(ismember(YourArray, look_for));
This version looks for exact matches against what is in look_for, but does not depend upon the array being sorted and does not depend upon any particular value being present.
Fabio Taccaliti
el 30 de Jun. de 2022
Walter Roberson
el 30 de Jun. de 2022
loc0 = find(YourArray == 0, 1, 'first');
%use this
loc2F = find(YourArray == 2, 1, 'first');
subsetF = YourArray(loc0:loc2F-1);
%OR use this
loc2L = find(YourArray == 2, 1, 'last');
subsetL = YourArray(loc0:loc2L);
Categorías
Más información sobre Matrix Indexing 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!