function [localSolution, rtx] = iterApplyA(localA, x, r0, tran, partition, n)
% ITERAPPLYA multiplies a vector x by distributed sparse matrix A.  It uses
% local part of A distributed by rows for the 'notransp' case and the local
% part of A distributed by columns (the transpose of the local partof A 
% distributed by rows) for the 'transp' case.  The routine does the
% necessary communication.  If a second output is requested, it also
% calculates r0'*A*x.

%   Copyright 2018-2022 The MathWorks, Inc.

switch tran
    case 'notransp'
        x = spmdCat(x, 1);    % Get all of x
        solution = distributedutil.iterapp('mtimes', localA.fun, localA.type, ...
                 x, tran);
        if ~strcmp(localA.type, 'matrix')
            localSolution = solution(partition, 1);
        else
            localSolution = solution;
        end
    case 'transp'
        if ~strcmp(localA.type, 'matrix')
            xFull = zeros(n, 1);
            xFull(partition) = x;
            x = xFull;
        end
        solution = distributedutil.iterapp('mtimes', localA.tfun, localA.type, ...
                 x, tran);
        solution = full(spmdPlus(solution));  % whole solution vector
        localSolution = solution(partition, 1); % local part of solution
end

if nargout > 1
    rtx = r0'*localSolution;
    rtx = spmdPlus(rtx);
end
end
