find 'last' function not working
显示 更早的评论
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 个评论
Simon Chan
2022-7-11
What are the results when you do the following:
[r,c] = find(~isnan(Monotonic),1,'last');
Vasileios Papavasileiou
2022-7-11
采纳的回答
更多回答(2 个)
Bruno Luong
2022-7-11
编辑:Bruno Luong
2022-7-11
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)
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!