Search code examples
matlabnormalizationangle

normalize angles from [-180,180] to [0,180]


I have servo motor can rotate from 0 to 180 only And I have angles range from -180 to 180 to send to servo how can i normalize between those two ranges?? And if there is any MATLAB function to do that?? thanks


Solution

  • You could Add 180 and divide by 2 as @High Performance Mark suggests for your specific problem or here is a generalized version of it based on This post.

    This equation holds good for any limits

    I have written a simple function based on the equation:

    function [out] = normalizeLim( A,oldL,oldR,newL,newR )
    
        out = newL*(1-((A-oldL)./(oldR-oldL))) + newR*((A-oldL)./(oldR-oldL));
    
    end
    

    Example:

    x = randi([-180,180],1,8); %//  Generating a random vector within the range -180 to 180
    
    >> x
    
    x =
    
    -153  -161    11   101   157  -134    25   -11
    
    >> normalizeLim(x,-180,180,0,180) %// Specifying old and new required limits
    
    ans =
    
    13.5000    9.5000   95.5000  140.5000  168.5000   23.0000  102.5000   84.5000
    

    If you want them as integers, you might round them using round function

    Hope this helps!!