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.
댓글 수: 0
채택된 답변
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
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
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개)
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!