MATLAB: Create symbolic matrix from triplets with repeated indices

accumarraysparsesymbolic

Hi everyone,
I am trying to build a symbolic matrix from the triplets iRow, jCol, aElm such that
A(iRow(k),jCol(k)) = A(iRow(k),jCol(k))+aElm(k)
the work can be easily done with 'sparse' or 'accumarray', but my vector aElm is symbolic and these functions do not defined for input arguments of type 'sym'. I may use linear indexing, however the iRow and jCol vectors contains repeated indices and the values must be summed up in the final matrix. A for-loop gets the job done, but I am looking for a cleaner vectorised way, if possible. Suggestions?
Example
syms a1 a2 a3 a4
iRow = [1 2 1 2];
jCol = [1 1 1 2];
aElm = [a1 a2 a3 a4];
% expected result
A =
[ a1 + a3, 0]
[ a2, a4]
Thank you in advance!
Fabio

Best Answer

iRow = [1 2 1 2];
jCol = [1 1 1 2];
aElm = sym('a',[1 4])
k = accumarray([iRow(:),jCol(:)],(1:numel(iRow))',[],@(x){x});
s = size(k);
out = zeros(s,'sym');
for jj = 1:numel(k)
out(jj) = sum(aElm(k{jj}));
end
out = reshape(out,s)