フィルターのクリア

How to find the index of the first and last non-zero value of a vector ?

21 ビュー (過去 30 日間)
Adnan Hayat
Adnan Hayat 2020 年 12 月 14 日
編集済み: Adnan Hayat 2020 年 12 月 15 日
Hello, I have a vector suppose a function f(x), such that
f(x)= ...0,0,0,0,0,0,0,0,5,6,7,4,3,5,6,7,8,0,0,0,0,0,0,0... and
x = 1,2,3,4,5,....
I don't know which command can I use to find those values of x for which the values of f(x) are 5 and 8 (i.e the first and last non-zero values)?

採用された回答

Daniel Pollard
Daniel Pollard 2020 年 12 月 14 日
編集済み: Daniel Pollard 2020 年 12 月 14 日
The built in command find sounds like what you need. The code could look something like
f = ...0,0,0,0,0,0,0,0,5,6,7,4,3,5,6,7,8,0,0,0,0,0,0,0...;
x_idx = find(f);
x = [x_idx(1), x_idx(end)];
where x is the positions of the first non-zero component and the last non-zero component.
Edit To correct a mis-type.
  7 件のコメント
Rik
Rik 2020 年 12 月 14 日
Note that f_x=f(x);ind=[find(f_x,1,'first') find(f_x,1,'last')]; might be faster, as the JIT might be able to optimize this call.
Adnan Hayat
Adnan Hayat 2020 年 12 月 15 日
編集済み: Adnan Hayat 2020 年 12 月 15 日
Thank you both, I got my issue resolved :)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by