The correct way to retrieve indices and values ​​of non-NaN elements in an array

I have a data array with numbers and NaN elements. I would like to get 3 vectors with indices and corresponding values ​​of elements other than NaN of this array.

Here is how I do it:

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

Now this is not optimal. At first, the size zis different from the size xand y(this is one element shorter, and I do not know which one was omitted). Secondly, I am sure that this can be done on one line.

+4
source share
2 answers

find , , :

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

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

find isnan , . , A:

[ii,jj] = find(~isnan(A));
z = A(sub2ind(size(A),ii,jj))

sub2ind, ii+(jj-1)*size(A,1).

ii jj , A(~isnan(A)), z ( find).

+2

Source: https://habr.com/ru/post/1524138/


All Articles