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!