Rounding numbers using a condition?

4 ビュー (過去 30 日間)
shellmcg
shellmcg 2016 年 4 月 28 日
コメント済み: Roger Stafford 2016 年 4 月 29 日
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.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by