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.
0 个评论
采纳的回答
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!