Efficient way of storing a triangular matrix
Show older comments
Hi all,
I have some pretty large upper triangular matrices to store and to be used like this:

As you see, these matrices are full in upper triangle and zeros in lower triangle. However, Matlab is not optimised to store such matrices, using sparse only makes the memory cost slightly larger.
So shall I vectorise these matrices to vectors, such that Matlab only stores the real numbers, and then after the operations I change them back to upper triangular matrices? If I should, is there any efficient functions to achieve this?
Many thanks!
Accepted Answer
More Answers (1)
David Goodmanson
on 17 Feb 2018
Edited: David Goodmanson
on 17 Feb 2018
Hi Xiaohan,
Since you have several matrices, one option is to store them in pairs as a square matrix (plus one extra column). For upper triangular M1,M2:
n = size(M2,1);
d2 = diag(M2);
M2(1:n+1:n^2) = 0;
M12 = [M1 + M2.' d2]; % n x (n+1) to store
% other direction
d2 = M12(:,end);
M12(:,end) = [];
M1 = triu(M12);
M2 = tril(M12).';
M2(1:n+1:n^2) = d2;
I don't claim that this process is necessarily speedy, but if storage is an issue it does not waste space.
3 Comments
Xiaohan Du
on 19 Feb 2018
Edited: Xiaohan Du
on 19 Feb 2018
David Goodmanson
on 26 Feb 2018
Hi Xiaohan,
I like the visual appeal of storing two matrices as a matrix, but aside from that I think John's method has most of the advantages. Besides its being slightly faster, you can deal with one matrix at a time, not two. Creating Boolind itself is fast enough that I don't think you need to store it, and for several matrices of the same size you only need to create it once. And since you are storing matrices as vectors, within memory limitations you can even stack a few of the storage vectors and make a matrix of that if you wish.
Xiaohan Du
on 28 Feb 2018
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!