How can I find the index and value of the smallest element within a range of values in a vector
8 views (last 30 days)
Show older comments
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 Comments
Answers (2)
Adam
on 13 Nov 2015
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 Comments
James Tursa
on 13 Nov 2015
Edited: James Tursa
on 13 Nov 2015
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 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!