Round to the nearest 0.5 in matlab

How can I round a decimal number to the nearest 0.5 in matlab? For instance. I want 16.625 to be rounded to 16.5

+5
source share
3 answers

This is the same logic, the same question was made for C #

result = round(value*2)/2;

And to summarize, as suggested by aardvarkk , if you want to round to the nearest precision acc, for example acc = 0.5:

acc = 0.5;
result = round(value/acc)*acc;
+12
source

If you go to multiply by 2 - round - division by 2 routes, you may get some (very small) numerical errors. You can do this using modto avoid this:

x = 16.625; 
dist = mod(x, 0.5); 
floorVal = x - dist; 
newVal = floorVal; 
if dist >= 0.25, newVal = newVal + 0.5; end

, , , .

+3
a=16.625;
b=floor(a);
if abs(a-b-0.5) <= 0.25
  a=b+.5;
else
  if a-b-0.5 < 0
    a=b;
  else
    a=b+1;
  end
end
+1

All Articles