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.

有帮助吗?

解决方案

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(:));

其他提示

You don't need to call find or isnan twice since you get the subscripts with the first command. Apply them to get the values in A:

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

If you are opposed to sub2ind, you can use ii+(jj-1)*size(A,1).

In the event that you you do not need ii and jj later, you can just do A(~isnan(A)) to get z (no find needed).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top