Code covered by the BSD License  

Highlights from
Recursive HYPOT Function for Multiple Inputs

Recursive HYPOT Function for Multiple Inputs

by

 

01 Mar 2012 (Updated )

Extension of the built-in MATLAB function hypot for multiple inputs.

hypotr(varargin)
function y = hypotr(varargin)

% HYPOTR Recursive hypot function for multiple inputs.
% 
% Usage: Y = HYPOTR(X) or Y = HYPOTR(X1, X2, X3, ...)
% 
% This function works the same as the built-in MATLAB function hypot but
% allows for more than two inputs (or a single array) via recursion. The
% output Y is:
% 
% Y = sqrt(sum(X(:).^2))                (for single array X input)
% Y = sqrt(X1.^2 + X2.^2 + X3.^2 + ...) (for arrays X1, X2, X3, ... input)
%
% But the computation is done in a more robust way to avoid overflow and
% underflow (see HYPOT). Note that when multiple arrays are input, they
% must all be the same size (but any or all of them can also be scalars).
% 
% See also: HYPOT.

error(nargchk(1, Inf, nargin));

% With only input, do hypot on each term.
if nargin == 1
    % Just output the input if the input is a scalar.
    if numel(varargin{1}) == 1
        y = varargin{1};
        return;
    % Otherwise, convert the single input into a cell array.
    else
        varargin = num2cell(varargin{1});
    end
end

% Call hypot recursively.
y = hypot(varargin{1}, varargin{2});
for index = 3:numel(varargin)
    y = hypot(y, varargin{index});
end

Contact us