Question

I have an array:

[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]

I want to set new numbers in range of [0 0.5 1] for the above array. For example, 0.5238 is nearer to 0.5 than 1, so it should be set to 0.5 rather than 1. 0.0025 is closer to 0 than 0.5, so it should be set to 0, and so on. As a result, new array should be:

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

How is it possible in MATLAB? Is there any function?

Was it helpful?

Solution

Something like this is a little bit better than assuming it as simple as 0.5. If you know the values that you want to round closest to.

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

You can also do this in a very optimized way without the 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);

OTHER TIPS

I think that you want to use the round function with a scale factor:

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top