I have a cell array of 10 or so elements, and the first few values are NaN. I want to display the first non NaN value in the column and assign it to a variable. For Example:
A = {NaN; NaN; NaN; NaN; 1; 2; 3; 4; 6; 8};
B = 'first non NaN value'
Any quick one liners to pull this value?

 채택된 답변

Star Strider
Star Strider 2017년 6월 22일

1 개 추천

See if this does what you want:
B = A(find(cellfun(@(x)~isnan(x), A) == 1, 1))

댓글 수: 5

Paxton Carnes
Paxton Carnes 2017년 6월 22일
This does work on cell arrays. As a follow up, how would I do the same thing on a regular double array?
That’s essentially the same code. It’s easier, since it doesn’t need the cellfun function:
A = [NaN; NaN; NaN; NaN; 1; 2; 3; 4; 6; 8];
B = A(find(~isnan(A) == 1, 1))
Paxton Carnes
Paxton Carnes 2017년 6월 22일
This works! Thank you.
Jan
Jan 2017년 6월 22일
편집: Jan 2017년 6월 22일
+1. And you do not need an anonymous function:
B = A{find(~cellfun(@isnan, A), 1)}
Anonymous functions in cellfun are slower than function handles.
A = num2cell(rand(1, 1000));
tic; for k=1:100; B=A{find(cellfun(@(x)~isnan(x), A)==1, 1)}; end; toc
tic; for k=1:100; B=A{find(~cellfun(@isnan, A), 1)}; end; toc
Elapsed time is 0.663674 seconds.
Elapsed time is 0.146717 seconds.
In addition, the code is leaner, such that there are less chances for typos ;-)
Star Strider
Star Strider 2017년 6월 22일
@Paxton Carnes — My pleasure!
@Jan — Noted. Thank you for the vote! (The anonymous function was part of an initial experiment. I forgot to simplify it in my final Answer for the cell, but did in my code for the vector.)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

질문:

2017년 6월 22일

댓글:

2017년 6월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by