function sliceA = extractSlice(A, dim, slice)
% Helper to extract an (N-1)D slice of an ND array in the specified
% dimension. Allowed values of SLICE are "first", "last", or a positive integer
% index. Requesting a slice beyond the size of the data will return a correctly
% dimensioned empty result. This applies to empty arrays too.

% Copyright 2018 The Mathworks, Inc.

sizeInDim = size(A, dim);

if isstring(slice)
    assert(ismember(slice, ["first", "last"]), ...
        "Slice must be an index or ""first""/""last"".");
    if strcmp(slice, "first")
        slice = 1;
    else
        slice = max(1, sizeInDim);
    end
else
    assert(isnumeric(slice) && isscalar(slice) && slice>0, ...
            "Slice must be a valid index or ""first""/""last"".");
end

subs = repmat({':'}, 1, max(ndims(A), dim));
if slice>sizeInDim
    % Empty result, but other dimensions must be preserved
    subs{dim} = [];
else
    subs{dim} = slice;
end
sliceA = subsref(A, substruct("()", subs));

end
