function out = extractSlices(in, rows, dim)
%EXTRACTSLICES copies out some elements from a slice of a multidimensional
%array.
%elements
%   Inputs:  in     A multidimensional array.
%            rows   Which slices of the array to copy out.
%            dim    The dimension from which to copy selectively.
%                   All other dimensions are copied completely.
%   Output   out    The copied array.
% out = in(:, :, ... rows, :, ...) where rows is the dim'th argument.

%   Copyright 2021 The MathWorks, Inc.

inputIsCodist = cellfun(@iscodistributed, {in, rows});
if any(inputIsCodist)
    inputIndex = find(inputIsCodist);
    for ix = inputIndex
        switch ix
            case 1
                codistributed.pVerifyUsing1d('assignSlices', in);
            case 2
                codistributed.pVerifyUsing1d('assignSlices', rows);
        end
    end
end
inIsCodist = inputIsCodist(1);
inDistNotOnDim = false;
if inIsCodist
    codistIn = getCodistributor(in);
    inDistNotOnDim = codistIn.Dimension ~= dim;
end
if inDistNotOnDim
    szOut = size(in);
    in = getLocalPart(in);
end
subsArg = repmat({':'}, 1, ndims(in));
subsArg(dim) = {rows};
subs = substruct('()', subsArg);
out = subsref(in, subs);
if inDistNotOnDim
    szOut(dim) = numel(rows);
    codistOut = codistributor1d(codistIn.Dimension, codistIn.Partition, szOut);
    out = codistributed.pDoBuildFromLocalPart(out, codistOut);
elseif inIsCodist
    out = gather(out);
end
