find n-st element that meet a logical expression

1 回表示 (過去 30 日間)
Yona
Yona 2014 年 12 月 7 日
編集済み: Yona 2014 年 12 月 8 日
I have 2 question: 1) find function can give the all n-th element (first or last) that meet a logical expression. i want only the second one, can i do it in one line. i need it for a for-loop, i want to start from the second one. now i do it by:
h = find(f==condition,2);
for i=h(end):length(g)
...
can we have a way to do it in 1 line (and not use variable h)?
2) i have a vector contain numbers, i want ignore all 0 and find the place of first one that change his sign from the previous ones.
for example, in array r=[0 0 -2 -3 0 0 4 0 5 -2], my result is the place of 4 (7th).
i use find and diff to find it but it give me 3 (the place in vector not include 0):
find(diff(sign(r~=0))~=0,1)+1
how can i find it?

採用された回答

Henrik
Henrik 2014 年 12 月 7 日
I can't think of a way to do your question 1 in one line of code, but is it really that important to remove one line of code?
For your question #2, this should do the trick. I suppose there's a way to do it with fewer lines, but this was the best I could come up with.
r=[0 0 -2 -3 0 0 4 0 5 -2];
r_no_zero=r(r~=0);
r_sign_change=find(diff(sign(r_no_zero),1))+1;
find(r==r_no_zero(r_sign_change(1)))
  1 件のコメント
Yona
Yona 2014 年 12 月 8 日
編集済み: Yona 2014 年 12 月 8 日
#1 is not important it only a question of aesthetic and i ask to see if MATLAB has a way that i don't know to do it.
#2 it's good. finally, i do it different:
r=[0 0 -2 -3 0 0 4 0 5 -2];
r_no_zero=r(find(r~=0,1));
find(sign(r)~=sign(r_no_zero) & r ~= 0,1)
i don't like the double use on find for this...
thank you, hope to get some more answer.

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

その他の回答 (0 件)

カテゴリ

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