How can I find the index and value of the smallest element within a range of values in a vector
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Adam
am 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 Kommentare
James Tursa
am 13 Nov. 2015
Bearbeitet: James Tursa
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!