问题
I have a variable of equidistant values (suppose values=0:1e-3:1
). I want to get the value and its correspondent index from values
which is closest to a uniformly random value (suppose x=rand
).
I could do [value,vIdx]=min(abs(values-x))
, which would be the simplest minimization I could do. Unfortunately the min
function won't take advantage from one property from the data, that is to be convex. I don't need to search all indexes, because as soon as find an index that is no more lesser than the previous I've found the global minimum. Said that, I don't want to substitute the matlab min function for a loop that would be slower depending on how distant it is from the value I will start. There are many methods that could be used, as the golden section, but I am not sure if using matlab fmincon would be faster than the min
method.
Does anyone have any hints/ideas how to get the required value faster than using the described min
method? I'll check the time performance when I have time, but if someone knows a good answer a priori, please let me know.
Possible Application: Snap to nearest graphic data
回答1:
Since your points are equidistant you can use the value x
to find the index:
vIdx = 1+round(x*(numel(values)-1));
The idea is that you are dividing the interval [0, 1]
into numel(values)-1
equally sized intervals. Now by multiplying x
by that number you map the interval to [0, numel(values)-1]
where your points are mapped to integer values. Now using round
you get the closest one and by adding 1 you get the one-based index that MATLAB requires.
来源:https://stackoverflow.com/questions/18349081/minimization-of-convex-stochastic-values