function perTri = perVertextoperTriangle( tricellvxs, perVx, triangles )
%perVx = perVertextoperFE( tricellvxs, perVx, triangles )
%   Given a quantity that is defined for each vertex of a triangular mesh,
%   calculate an equivalent quantity per triangle.
%
%   The per-vertex quantity can be a vector.  If m has numVx vertexes and
%   numFEs finite elements, then perVx has size  [numVxs,K] for some K, and
%   perTri has size [numFEs,K]. 
%
%   Note that this is an approximation: some smoothing is unavoidable in
%   the calculation.  The function perFEtoperVertex translates the other
%   way, but these two functions are not inverses.  Converting back and
%   forth will have the side-effect of spreading out the distribution of
%   the quantity.

    numdims = size(perVx,2);
    if numdims==1
        if nargin < 3
            perTri = sum( perVx( tricellvxs ), 2 )/size(tricellvxs,2);
        else
            perTri = sum( perVx( tricellvxs(triangles,:) ), 2 )/size(tricellvxs(triangles,:),2);
        end
    else
        if nargin < 3
            perTri = permute( sum( reshape( perVx( tricellvxs', : ), 3, [], numdims ), 1 ) ...
                              / size(tricellvxs,2), ...
                              [2,3,1] );
        else
            perTri = permute( sum( reshape( perVx( tricellvxs(triangles,:)', : ), 3, [], numdims ), 1 ) ...
                              / size(tricellvxs(triangles,:),2), ...
                              [2,3,1] );
        end
    end
end
