Aditya
Aditya

Reputation: 43

first non NaN element value and index in matlab

I want to obtain value and index of first non-NaN element from each column of a matrix in the matlab.

In a separate problem--- There are few columns that does not have NaN. So in that case-- I would like to extract value and index of first non-NaN element from each column and otherwise first element of each column if column does not contain NaN.

Can anybody help regarding these two problems?

Upvotes: 2

Views: 1872

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112759

The index is easily obtained with the second output of max. The value can be found from that index using sub2ind or computing the corresponding linear index manually.

To return a different index in columns that contain all NaN, use the first output of max to detect that situation and change the result for those columns.

Let x denote your matrix. Then:

[m, index]  = max(~isnan(x), [], 1);
value = x(index + (0:size(x,2)-1)*size(x,1));
        %// or equivalently x(sub2ind(size(x), index, 1:size(x,2)))
index(~m) = size(x, 1); %// return last index for columns that have all NaN

Example

x = [  8    NaN     3    NaN
      NaN     4     5    NaN];

produces

index =
     1     2     1     2
value =
     8     4     3   NaN

Upvotes: 3

Related Questions