Rounding each individual value in a vector to values in another vector

2 views (last 30 days)
If you have v1 = [2.5 3.74 7.92] (These numbers are meant to be random) and you wanted to round these numbers up or down, you use floor(v1) or ceil(v1). But what if you wanted to round these numbers to other values instead of integers? Say you want to round them to the values in vector v2 = 1.25:10.25. How would you go about doing it without using a for loop?
Such that:
"function"(v1,v2) = [2.25 3.25 7.25] %Rounding to the left "function"(v1,v2) = [3.25 4.25 8.25] %Rounding to the right
I know that one method is
for i = 1:length(v1) v2(find(v1(i)-v2>0,1,'last')); % Nearest lower end
for i = 1:length(v1) v2(find(v1(i)-v2<0,1,'first')); % Nearest higher end
However, this method involves a for loop. Is there a more elegant method with only vectorization involved?
Thanks for your help.

Accepted Answer

Jan
Jan on 15 Jul 2013
Edited: Jan on 15 Jul 2013
v1 = [2.5 3.74 7.92];
v2 = 1.25:10.25;
interp1(v2, v2, v1, 'nearest')
You can modify the code of INTERP1 to get the next lower or higher values also.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!