Given a set of numbers, like
A={{1,2.5,3},
{4.2,7,10}};
and another set of numbers, like
B={1,2,3,4,5};
Is there a fast algorithm to round A to the nearest values in B?
result = {{1,3,3},
{4,5,5}};
we can write a intuitive program with Matlab by calculating the distance of every element of A with all the values in B, and get the index of the number with "min" in Matlab, but is there a faster way to do this?
The current method relies on enumerating over every element in A, is there a method to enumerate row by row, or over the whole set at once?
Best Answer
If you have the data in the form of numeric arrays (that is,
A
is a matrix andB
is a vector, as opposed to cell arrays as in your example), it can be done in one line, usinginterp1
with the'nearest'
and'extrap'
options. The former option specifies nearest-neighbour method of interpolation; the latter indicates that values may be outside the original range. See documentation for further details.