Search code examples
matlabmathrounding

Round to the nearest odd multiple of a number


is there a MATLAB function that can round to the nearest odd multiple of a number? For instance, if x = 1.1 and the number is 0.5, then x should be rounded to 1.5

I could come up with a function to round to the nearest multiple but not the nearest odd multiple

x = round(x*(1/number))/(1/number);

Solution

  • You need to modify your approach as follows:

    • Use twice the step, that is, 2*number;
    • Shift the input by half of the new step;
    • Undo the shifting in the output.
    y = round((x/(2*number)-.5))*(2*number)+number;
    

    Example:

    number = 2.5;
    x = [-10:.01:10];
    y = round((x/(2*number)-.5))*(2*number)+number;
    plot(x,y)
    grid on, axis equal, axis([-15 15 -12.5 12.5])
    

    enter image description here