function [fullC, lia] = setfunExtractMatch(A, localLia, isRows)
%SETFUNEXTRACTMATCH Return all members (rows if isRows) of A that are
% referenced in logical vector localLia.
%
%   localLia must have the same number of elements (or rows) as the local
%   part of A.

%   Copyright 2023 The MathWorks, Inc.

if iscodistributed(A)
    localA = getLocalPart(A);
    codistA = getCodistributor(A);
    distDimA = codistA.Dimension;
    partA = codistA.Partition;
else
    localA = A;
end

% Construct fullC (C before removal of duplicates within A).
if isRows
    localC = localA(localLia, :);
    colsC = size(A, 2);
    if iscodistributed(A) 
        if distDimA == 2
            partC = spmdCat(size(localC, 2), 2);
            codistC = codistributor1d(2, partC, [size(localC, 1), colsC]);
        else
            partC = spmdCat(size(localC, 1), 2);
            codistC = codistributor1d(1, partC, [sum(partC), colsC]);
        end
        fullC = codistributed.pDoBuildFromLocalPart(localC, codistC);
    else
        fullC = localC;
    end
    % Build distributed lia for output to use later.
    if iscodistributed(A) && distDimA == 1
        codistLia =  codistributor1d(1, partA, [size(A, 1) 1]);
        lia = codistributed.pDoBuildFromLocalPart(localLia, codistLia);
    else
        lia = localLia;
    end
else
    if iscodistributed(A)
        localLia = reshape(localLia, size(localA));
        lia = codistributed.pDoBuildFromLocalPart(localLia, codistA);
    else  % Even though A was not codistributed, fullC needs to be.
        A = codistributed.pConstructFromReplicated(A);
        lia = localLia;
    end
    fullC = subsref(A, substruct('()', {lia}));
end
end
