How can I find the index and value of the smallest element within a range of values in a vector

1 vue (au cours des 30 derniers jours)
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?

Réponses (2)

Adam
Adam le 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.

James Tursa
James Tursa le 13 Nov 2015
Modifié(e) : James Tursa le 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);

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by