5
votes

I have a large sparse matrix, and I want to permute its rows or columns to turn the original matrix into a block diagonal matrix. Anyone knows which functions in R or MATLAB can do this? Thanks a lot.

4
the question is not perfectly clear but in R you can use permute package.agstudy
Start here: stackoverflow.com/questions/5963269/… show us what you have (or do your best to show us what you have) and show us what you want it to look like afterwards. Toy examples are just fine.Brandon Bertelsen
Try first to cluster your data using ?hclust. You may define a distance between each couple of rows (column) of your array say a and b just by computing abs(a-b). Then hclust() will return you a good permutation that puts every row (and column) close to ones having non-zero values on the same indicesAli
A simpler method would be to use pheatmap() of package pheatmap. It will provide you a visualization of your block-diagonal matrix.Ali

4 Answers

2
votes

I'm not really set up to test this, but for a matrix m I would try:

p = symrcm(m);
block_m = m(p,p);

If that doesn't work, look through the other functions listed in help sparfun to see if any will help you out.

1
votes

The seriation package in R has a number of tools for problems related to this one.

1
votes

Not exactly sure if this is what you want, but in MATLAB this is what I have used in the past. Probably not the most elegant solution. I go from sparse to full and then chop the thing into square blocks.

A=full(A);

Then:

blockedmatrix = mat2cell(A, (n*ones(1,size(A,1)/n)), ...
(n*ones(1,size(A,1)/n))); %found somewhere on internetz

This returns a cell, where each entry is of size nxn. It's easy to extract the blocks of interest, manipulate them, and then restore them to a matrix with cell2mat.

1
votes

Maybe a bit late to the game, but since there are available commands, here is a simple one. If you have a matrix H and the block diagonal form is needed, you can obtain it through the following lines (MATLAB):

[p,q] = dmperm(H);
H(p,q)

which is equivalent to Dulmage - Mendelsohn permutation.