function varargout = bandwidth( A, whichOutput )
%BANDWIDTH  Return the lower and upper bandwidth of a codistributed matrix.
%   
%   [LOWER,UPPER] = bandwidth(X)
%   LOWER = bandwidth(X,'lower')
%   UPPER = bandwidth(X,'upper')
%   
%   Example:
%   spmd
%      A = codistributed([2 3 0 0 ; 1 -2 -3 0; 0 -1 2 3 ; 0 0 -1 2]);
%      [lower, upper] = bandwidth(A,1,1) % = 1, 1
%   end
%   
%   See also ISBANDED, CODISTRIBUTED, CODISTRIBUTED/ISBANDED.
%   


%   Copyright 2016-2022 The MathWorks, Inc.

% Check nargin and nargout match
if nargin == 1
    nargoutchk(1,2);
end

% This function works for double, single and logical
if ~(isfloat( A ) || islogical( A ))
    error(message('MATLAB:bandwidth:inputType'))
end

% Also error for ND arrays
if ~ismatrix( A )
    error(message('MATLAB:bandwidth:inputMustBe2D'));
end

% Get the actual bandwidths from metadata to avoid recalculation.
if ~A.Metadata.Bandwidth.isKnown()
    getFillPattern(A); % Force recalculation of fill-related metadata
end
bands = A.Metadata.Bandwidth.get();
lower = bands(1);
upper = bands(2);

% Handle optional second argument
if nargin == 2
    if strcmpi(whichOutput, 'lower')
        varargout{1} = lower;
    elseif strcmpi(whichOutput, 'upper')
        varargout{1} = upper;
    else
        error(message('MATLAB:bandwidth:unknownArgument'));
    end
    if nargout == 2
        error(message('MATLAB:bandwidth:twoInOneOut'));
    end
else
    [varargout{1:2}] = deal(lower, upper);
end

end
