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!