Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding off to nearest 0.5 in matlab

Tags:

math

matlab

How can I round off a decimal to the nearest 0.5 in matlab? E.g. I want 16.625 to be rounded to 16.5

like image 239
Saad Pervez Avatar asked Mar 26 '13 14:03

Saad Pervez


3 Answers

It's the same logic, the same question was made for C#

result = round(value*2)/2;

And to generalize, according to aardvarkk's suggestion, if you want to round to the closest accuracy acc, for example acc = 0.5:

acc = 0.5;
result = round(value/acc)*acc;
like image 107
George Aprilis Avatar answered Oct 22 '22 14:10

George Aprilis


If you go the multiply by 2 - round - divide by 2 route, you may get some (very small) numerical errors. You can do it using mod to avoid this:

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

You could do it in fewer steps, but here I have broken it up so you can see what each step does.

like image 45
wakjah Avatar answered Oct 22 '22 13:10

wakjah


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
like image 1
PaxRomana99 Avatar answered Oct 22 '22 14:10

PaxRomana99