# Find first non-NaN in each column of array & combine into one vector

18 views (last 30 days)

Show older comments

I am trying to:

1) Identify the first non-NaN value of each column in an array, and convert the rest to NaN

2) Identify the first non-NaN value of each row in the array, and convert the rest to NaN

3) Combine these numbers back into one column vector

I have created something that looks roughly like this (although much larger):

X =

2 NaN NaN NaN

4 6 NaN NaN

NaN NaN NaN NaN

5 4 7 8

After the first step (keeping only the first number in each column), I would hope to have this:

Xa =

2 NaN NaN NaN

NaN 6 NaN NaN

NaN NaN NaN NaN

NaN NaN 7 8

After the second step (keeping only the first number in each row), I would hope to have this:

Xb =

2 NaN NaN NaN

NaN 6 NaN NaN

NaN NaN NaN NaN

NaN NaN 7 NaN

Lastly, I would want to turn this into one column (there should only be NaN's or 1 non-NaN value in each row - I would want it to keep whichever is there)

Xc =

2

6

NaN

7

I apologize for not having any attempted code for this. I appear to have gotten stuck in the doorway of this one...

##### 0 Comments

### Accepted Answer

Bruno Luong
on 19 Jul 2019

Edited: Bruno Luong
on 19 Jul 2019

X = [2 NaN NaN NaN;

4 6 NaN NaN;

NaN NaN NaN NaN;

5 4 7 8 ]

[m,n] = size(X);

[I,J] = ndgrid(1:m,1:n);

Xa = X;

[~,r]=max(isfinite(Xa),[],1);

Xa(I>r) = NaN

Xb = Xa;

[~,c]=max(isfinite(Xb),[],2);

Xb(J>c) = NaN

[~,c]=max(isfinite(Xb),[],2);

Xc = Xb(sub2ind([m,n],(1:m)',c))

##### 2 Comments

Adam Danz
on 19 Jul 2019

Be sure to add semicolons to the end of 3 lines that are missing them.

Also, use ~isnan() rather than isfinite().

### More Answers (2)

Adam Danz
on 19 Jul 2019

Edited: Adam Danz
on 19 Jul 2019

X = [2 NaN NaN NaN

4 6 NaN NaN

NaN NaN NaN NaN

5 4 7 8];

X(cumsum(cumsum(~isnan(X)))~=1) = NaN; % your Xa

X(cumsum(cumsum(~isnan(X),2),2) ~=1) = NaN; % your Xb

Xc = NaN(size(X,1),1);

Xc(any(~isnan(X),2)) = X(~isnan(X)); % your Xc

##### 2 Comments

Adam Danz
on 19 Jul 2019

Mario Chiappelli
on 19 Jul 2019

Check out this question asked earlier on the forum, I think it asks and answers what you want.

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!