0

我有一个数组:

[0.0182, 0.5238, -0.0205, 1.1683, 0.9684, 0.9722, 0.5677, 0.9043, 0.0025, ...
 0.9986, 0.4088, 0.5483, -0.0082, 0.5659]

我想[0 0.5 1]为上述数组设置范围内的新数字。例如, 0.5238is near to 0.5than 1, 所以应该设置为0.5而不是1。更0.0025接近于,因此应设置为,依此类推。因此,新数组应该是:00.50

[0, 0.5, 0, 1, 1, 1, 0.5, 1, 0, 1, 0.5, 0.5, 0, 0.5]

在 MATLAB 中怎么可能?有什么功能吗?

4

2 回答 2

1

我认为您想使用round具有比例因子的函数:

x = [0.0182, 0.5238, -0.0205, 1.1683, 0.9684, 0.9722, 0.5677, 0.9043, 0.0025, 0.9986, 0.4088, 0.5483, -0.0082, 0.5659]

roundingScaling = 0.5;
round(x/roundingScaling )*roundingScaling 
于 2013-07-16T18:58:36.763 回答
1

像这样的东西比假设它像 0.5 那样简单要好一点。如果您知道要四舍五入最接近的值。

valueToRoundTo = [0,0.5,1];
x = [0.0182, 0.5238, -0.0205, 1.1683, 0.9684, 0.9722, 0.5677, 0.9043, 0.0025, 0.9986, 0.4088, 0.5483, -0.0082, 0.5659];

for i = 1:numel(x)
    [~,idx] = min(abs(valueToRoundTo-x(i)));
    x(i) = valueToRoundTo(idx);
end

您也可以以非常优化的方式执行此操作,而无需for loop

valueToRoundTo = [-0.5,0,0.5,1];
x = [0.0182, 0.5238, -0.0205, 1.1683, 0.9684, 0.9722, 0.5677, 0.9043, 0.0025, 0.9986, 0.4088, 0.5483, -0.0082, 0.5659];
[~,idx] = min(abs(bsxfun(@minus,x,valueToRoundTo.')));
rounded = valueToRoundTo(idx);
于 2013-07-16T19:06:38.237 回答