Rounding numbers using a condition?
2 views (last 30 days)
Show older comments
shellmcg
on 28 Apr 2016
Commented: Roger Stafford
on 29 Apr 2016
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.
0 Comments
Accepted Answer
Roger Stafford
on 28 Apr 2016
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 Comments
Roger Stafford
on 28 Apr 2016
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
on 29 Apr 2016
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.
More Answers (1)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!