function t = tail(A,K)
%TAIL Get last rows of codistributed array.
%   
%   TAIL(X) displays the last eight rows of the codistributed array X in
%   the command window without storing a value.
%   
%   TAIL(X,K) displays up to K rows from the end of the codistributed array
%   X. If X contains fewer than K rows, then the entire array is
%   displayed.
%   
%   Y = TAIL(X) or Y = TAIL(X,K) returns the last eight rows, or up to K
%   rows, of the codistributed array X.
%   
%   See also: TAIL, CODISTRIBUTED/HEAD, CODISTRIBUTED.
%   
%   


%   Copyright 2016-2022 The MathWorks, Inc.

if nargin<2
    K = matlab.bigdata.internal.util.defaultHeadTailRows();
else
    % Check that k is a non-negative integer-valued scalar
    validateattributes(K, ...
        {'numeric'}, {'real','scalar','nonnegative','finite','integer'}, ...
        'tail', 'k')
end
if K>size(A,1)
    % Not enough rows, so return everything
    tmp = A;
else
    subs = repmat({':'},1,ndims(A));
    N = size(A,1);
    subs{1} = N+(1-K:0);
    subs{1} = matlab.internal.ColonDescriptor(N+1-K,1,N);
    tmp = subsref(A, substruct('()',subs));
end

% As of R2023a, tail is also available for numeric arrays. It follows the
% same startegy to display and not set ANS when no output is requested.
if nargout==0
    disp(tmp);
else
    t = tmp;
end