Rounding numbers using a condition?

3 次查看(过去 30 天)
I have an array of numbers ranging from 95 to 116. I would like to have the numbers closest to 99 in value be 99, the numbers closest to 104 in value be 104 and the number closest to 115 in value be 115. How could code this? Thanks for the help.

采纳的回答

Roger Stafford
Roger Stafford 2016-4-28
Let the "numbers ranging from 95 to 116" be in a row vector u, and the numbers 99, 104, and 115 be in a column vector v.
[~,ix] = min(abs(bsxfun(@minus,u,v)),[],1);
u = v(ix);
Then u will now be as required.
  3 个评论
Roger Stafford
Roger Stafford 2016-4-28
The bsxfun(@minus,u,v) part finds the difference between each value in v and each value in u. The result will be a rectangular matrix of differences, between u and v values with the different u values along the horizontal direction and v values changing along the vertical direction. The 'abs' operation converts these differencess to their absolute values. The min(...,[],1) step finds the minimum of these absolute in each column and thereby finds the closest v value to the u value for that column. The ix indexes these. The final operation v(ix) is just choosing for each u value the corresponding ix value which references that closest v value.
I suggest you break the operations up like this:
t1 = bsxfun(@minus,u,v);
t2 = abs(t2);
[~,ix] = min(t2,[],1);
and study t1, t2, and ix. You will see how they lead to the desired result.
Make sure u is a row vector, that is, it has only one row, and v is a column vector, meaning it has only one column.
Roger Stafford
Roger Stafford 2016-4-29
One could also make use of 'histc'. Using the same u and v I previously defined, do this:
w = sort(v);
x = [-inf;(w(1:end-1)+w(2:end))/2;inf];
[~,ix] = histc(u,x);
u = w(ix);
This would be more efficient if v were very long.

请先登录,再进行评论。

更多回答(1 个)

Steven Lord
Steven Lord 2016-4-28
Use interp1 with the 'nearest' method.

产品

Community Treasure Hunt

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

Start Hunting!

Translated by