Find all numeric values right after the NaN values in a column vector

2 ビュー (過去 30 日間)
Konstantinos Tsitsilonis
Konstantinos Tsitsilonis 2017 年 6 月 22 日
編集済み: Konstantinos Tsitsilonis 2017 年 6 月 22 日
Good evening,
I have a column vector such that
vec = [1 ; 2 ; 3 ; 4 ; Nan ; 5 ; 6 ; 7 ; 8 ; Nan ; 9 ; 10 ; 11 ; 12 ; Nan];
I would like to find extract the elements of the vector ''vec'' that are located right after the NaN, such that I would get a new vector:
new_vec=[5;9]
It is very easy to find the indices of all the NaN elements, however I don't know how to 'shift' those indices a place further to locate the values right after the NaN.
Thanks for your help in advance,
KMT

採用された回答

Jan
Jan 2017 年 6 月 22 日
編集済み: Jan 2017 年 6 月 22 日
index = isnan(vec);
result = vec([false; index(1:end-1)]);
Or in one line:
result = vec([false; isnan(vec(1:end-1))]);
This is "logical indexing" and "shifting" is simply to insert a FALSE at the beginning.
  1 件のコメント
Konstantinos Tsitsilonis
Konstantinos Tsitsilonis 2017 年 6 月 22 日
編集済み: Konstantinos Tsitsilonis 2017 年 6 月 22 日
Thanks for your answer it works perfectly, however I seemed to have run into another problem. In case my vector is
vec = [1 ; 2 ; 3 ; 4 ; nan ;nan;nan; 5 ; 6 ; 7 ; 8 ; nan ; 9 ; 10 ; 11 ; 12 ; nan]
Then this solution does not work. How could I generalise this for any number of consecutive ''nan'' at any point in the vector?

サインインしてコメントする。

その他の回答 (1 件)

James Tursa
James Tursa 2017 年 6 月 22 日
編集済み: James Tursa 2017 年 6 月 22 日
E.g.,
x = find(isnan(vec))+1;
x = x(x<=numel(vec)); % or x(x>numel(vec)) = [];
result = vec(x);

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by