MATLAB: Cuthill Mckee matrix reordering – include row & column labels in the reordering

cuthill-mckeeexcelrow and column labels

Hi Mathworks friends,
I am reordering a 32×32 matrix using the reverse Cuthill-Mckee algorithm, with the symrcm(S) command. However, the original matrix is an Excel file with text labels on each row and column. I need the labels to be reordered along with the numeric values. Any ideas? Thanks
For example, it looks like this before reordering, and when the rows/columns are reordered, I want the labels to also be reordered:
"apple" "orange" "pear" "banana"
"apple" 1 1 0 1
"orange" 1 1 0 1
"pear" 0 0 1 0
"banana" 1 1 0 1

Best Answer

Use the permutation vector returned by symrcm to reorder the names as well. To show the matrix with row and column names I'll use the matrix to create a table (or actually two tables, one for before and one for after reordering.)
names = {'apple', 'orange', 'pear', 'banana'};
A = [1 1 0 1; 1 1 0 1; 0 0 1 0; 1 1 0 1];
p = symrcm(A);
before = array2table(A, 'VariableNames', names, 'RowNames', names.')
after = array2table(A(p, p), 'VariableNames', names(p), 'RowNames', names(p).')