find 'last' function not working
Mostrar comentarios más antiguos
Hi,
I am using "find" function to identify the first and last row where no-NaN values can be found in an array, as below. The interesting fact is that while 'first' works fine and returns the first index, the 'last' result is a huge number which even exceeds the number of rows in my array. Any ideas on why this happens? Could it be a bug or am I doing a logical error?
Monotonic_first_index = find(~isnan(Monotonic),1,'first')
Monotonic_last_index = find(~isnan(Monotonic),1,'last');
2 comentarios
Simon Chan
el 11 de Jul. de 2022
What are the results when you do the following:
[r,c] = find(~isnan(Monotonic),1,'last');
Vasileios Papavasileiou
el 11 de Jul. de 2022
Respuesta aceptada
Más respuestas (2)
Bruno Luong
el 11 de Jul. de 2022
Editada: Bruno Luong
el 11 de Jul. de 2022
Beside using 'any'/'all', you might make two modifications to get what you want
[Monotonic_last_row, ~] = find(~isnan(Monotonic.' ),1,'last'); % transpose and 2-output call
Another possible solution, beyond calling find with two output arguments, is to call it with one output then convert the linear index into subscripts using ind2sub. This is particularly useful if the input to find is an N-dimensional array (with N > 2.)
rng default % for reproducibility
A = randi(10, 3, 4, 5);
linearIndices = find(A == 9)
Make a cell array to hold subscripts, one per dimension of the original array.
subscripts = cell(1, ndims(A));
Now fill in the elements of that cell array by treating it as a comma-separated list to call ind2sub with a number of outputs equal to the number of dimensions of A.
[subscripts{:}] = ind2sub(size(A), linearIndices)
Let's spot check one of the elements, say the third one.
r = subscripts{1}(3);
c = subscripts{2}(3);
p = subscripts{3}(3);
shouldBe9 = A(r, c, p);
fprintf("Element A(%d, %d, %d) is %d.\n", r, c, p, shouldBe9)
One final check with the hard-coded values (this is where the rng call comes in handy; I know that any time this example runs the A array will be the same so I can hard-code these values.)
A(2, 4, 2)
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!