Square root of sum of squares


c = hypot(a,b)


c = hypot(a,b) returns the element-wise result of the following equation, computed to avoid underflow and overflow:

c = sqrt(abs(a).^2 + abs(b).^2)

Inputs a and b must follow these rules:

  • Both a and b must be single- or double-precision, floating-point arrays.

  • The sizes of the a and b arrays must either be equal, or one a scalar and the other nonscalar. In the latter case, hypot expands the scalar input to match the size of the nonscalar input.

  • If a or b is an empty array (0-by-N or N-by-0), the other must be the same size or a scalar. The result c is an empty array having the same size as the empty input(s).

hypot returns the following in output c, depending upon the types of inputs:

  • If the inputs to hypot are complex (w+xi and y+zi), then the statement c = hypot(w+xi,y+zi) returns the positive real result

    c = sqrt(abs(w).^2+abs(x).^2+abs(y).^2+abs(z).^2)
  • If a or b is ±Inf, hypot returns Inf.

  • If neither a nor b is Inf, but one or both inputs is NaN, hypot returns NaN.

  • If all inputs are finite, the result is finite. The one exception is when both inputs are very near the value of the MATLAB® constant realmax. The reason for this is that the equation c = hypot(realmax,realmax) is theoretically sqrt(2)*realmax, which overflows to Inf.


Example 1

To illustrate the difference between using the hypot function and coding the basic hypot equation in M-code, create an anonymous function that performs the same function as hypot, but without the consideration to underflow and overflow that hypot offers:

myhypot = @(a,b)sqrt(abs(a).^2+abs(b).^2);

Find the upper limit at which your coded function returns a useful value. You can see that this test function reaches its maximum at about 1e154, returning an infinite result at that point:

ans =

ans =

Do the same using the hypot function, and observe that hypot operates on values up to about 1e308, which is approximately equal to the value for realmax on your computer (the largest double-precision floating-point number you can represent on a particular computer):

ans =

ans =

Example 2

hypot(a,a) theoretically returns sqrt(2)*abs(a), as shown in this example:

x = 1.271161e308;

y = x * sqrt(2)
y =

y = hypot(x,x)
y =

See Also

| |

Introduced before R2006a

Was this topic helpful?