Correct way of extracting indices and values of non-NaN elements in an array

arrays, find, matlab, matrix, nan

Solution

You don't need the second `find` at all, just a little bit of logical indexing that you were already using:

% Example data
A = rand(5);
A(A>0.5) = NaN;

iA = ~isnan(A);
[x,y] = find(iA);
z = A(iA(:));

Problem

I have a data array with numbers and NaN elements. I would like to get 3 vectors with the indices and the respective values of the non-NaN elements of this array. Here is how I do it: ``` [x,y]=find(~isnan(A)); [~,~,z]=find(A(~isnan(A))); ``` Now, this is not optimal. First the size of `z` differs from the size of `x` and `y` (it is one element shorter, and I don't know which one has been omitted). Second, I'm sure it's possible to do both in one line.

Original source