Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
last non-nan observation in a matrix

Subject: last non-nan observation in a matrix

From: Danielle Leblanc

Date: 13 Aug, 2010 14:33:04

Message: 1 of 4

Assume X=[1 2 3 NaN NaN; 1 3 6 5 NaN; 2 4 NaN NaN NaN];
is there a way to select the last non-nan observation in each row without running a loop? (i.e 3;5;4 in this case)

Subject: last non-nan observation in a matrix

From: Sean

Date: 13 Aug, 2010 14:43:25

Message: 2 of 4

"Danielle Leblanc" <danielleblanc2004@hotmail.com> wrote in message <i43l30$h0e$1@fred.mathworks.com>...
> Assume X=[1 2 3 NaN NaN; 1 3 6 5 NaN; 2 4 NaN NaN NaN];
> is there a way to select the last non-nan observation in each row without running a loop? (i.e 3;5;4 in this case)

One way:
X=[1 2 3 NaN NaN; 1 3 6 5 NaN; 2 4 NaN NaN NaN];

[r c] = find(~isnan(X)); %find indices of non nans
X(sub2ind(size(X),unique(r),accumarray(r,c,[],@max))) %Keep biggest column in each row.

-Sean

Subject: last non-nan observation in a matrix

From: Walter Roberson

Date: 13 Aug, 2010 14:50:10

Message: 3 of 4

Danielle Leblanc wrote:
> Assume X=[1 2 3 NaN NaN; 1 3 6 5 NaN; 2 4 NaN NaN NaN];
> is there a way to select the last non-nan observation in each row
> without running a loop? (i.e 3;5;4 in this case)

X(sub2ind(size(X),1:size(X,1),max(bsxfun(@times,~isnan(X),1:size(X,2)),[],2).'))

ans =
      3 5 4


Aren't you glad you asked? ;-)

Subject: last non-nan observation in a matrix

From: Danielle Leblanc

Date: 13 Aug, 2010 15:21:20

Message: 4 of 4

definitely I am glad.

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us