Search code examples
matlabmatrixsparse-matrix

create the complete symmetric matrix by copying the lower triangular of a sparse matrix in triplet format


As the subject line suggests, what would be the most efficient way to copy the lower triangular part of a sparse matrix to the upper triangular part and complete the matrix entries to create the symmetric sparse matrix?

Assume that I have the triplets I, J, X for the lower triangle including the diagonal. I am reading these arrays from a commercial program and for storage space reasons, I believe, they only store the lower triangular part.

Well I will start testing different options soon, but wanted to see if someone else has experienced this before or not.


Solution

  • You can use sparse:

    idx = I ~= J; %index of nondiagonals
    result = sparse([I;J(idx)], [J;I(idx)], [X;X(idx)]);
    

    Because sparse adds together elements in X that have duplicate subscripts in I and J we exclude diagonal elements when concatenating vectors.