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

조회 수: 2 (최근 30일)
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.

채택된 답변

Jan
Jan 2013년 7월 15일
편집: Jan 2013년 7월 15일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by