How can I find the index and value of the smallest element within a range of values in a vector
1 回表示 (過去 30 日間)
古いコメントを表示
So, I need to find the index and value of the smallest element in a vector within a particular range of values:
so something like
loVal=1;
hiVal=10;
testVals = [-1;3;8;20];
[val, idx]=min((testVals>loVal)&(testVals<hiVal));% gives the wrong values!
then I would like the answer to come back; val=3 idx=2
Obviously, this script doesn't work. I have tried putting it on two lines;
rangeTestVals=testVals>loVal&testVals<hiVal;
[val, idx]=min(testVals(rangeTestVals));
but that produces; val=3 idx=1
but '1' is the index in the subset of testVals values, not the index I want. Every way I try this is quite inelegant.
Any thoughts?
0 件のコメント
回答 (2 件)
Adam
2015 年 11 月 13 日
vals( vals <= lowVal ) = NaN;
vals( vals >= highVal ) = NaN;
[val,idx] = nanmin( vals );
Seems to work but isn't the most elegant approach perhaps. And obviously you would probably want to do it on a copy of your vector rather than in-place unless you don't want to use the vector again afterwards.
0 件のコメント
James Tursa
2015 年 11 月 13 日
編集済み: James Tursa
2015 年 11 月 13 日
You could add code to map the index back into the original vector. E.g.,
rangeTestVals = testVals>loVal & testVal<hiVal;
[val, idx] = min(testVals(rangeTestVals));
f = find(rangeTestVals);
idx = f(idx);
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!