2
votes

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?

1
The second part, as it stands now, is included in the first. What's the output for a column that has all NaNs?Luis Mendo
@Luis Mendo: Thanks a lot! What if I want the index of the last element from each such column that contains all NaNs?Aditya

1 Answers

3
votes

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