Extract first non NAN value in an array
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Paxton Carnes
am 22 Jun. 2017
Kommentiert: Star Strider
am 22 Jun. 2017
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?
0 Kommentare
Akzeptierte Antwort
Star Strider
am 22 Jun. 2017
See if this does what you want:
B = A(find(cellfun(@(x)~isnan(x), A) == 1, 1))
5 Kommentare
Jan
am 22 Jun. 2017
Bearbeitet: Jan
am 22 Jun. 2017
+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
am 22 Jun. 2017
@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.)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Operators and Elementary Operations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!