MATLAB: Sorting matrix by diagonal of submatrix

sorting matrix by diagonal of submatrix

Hi,
I have a matrix of m x m^2 and I want to find the diagonals of the sub matrices m x m, then rearrange the matrix A such that the sub matrix with the largest diagonal is first and the sub matrix with the lowest diagonal is last
E.g. For the matrix A = [A1 A2 A3]
A =
2 4 6 8 9 1 4 8 1
4 1 2 3 6 1 2 3 4
5 2 3 4 1 7 2 3 12
Sub matrix A1 has a diagnoal of 6 Sub matrix A2 has a diagonal of 21 Sub matrix A3 has a diagonal of 19
so the final output would be A = [A2 A3 A1]
A =
8 9 1 4 8 1 2 4 6
3 6 1 2 3 4 4 1 2
4 1 7 2 3 12 5 2 3
Thanks in advance

Best Answer

[~,ii] = sort(sum(reshape(A(repmat(eye(3),1,3)>0),3,[])),'descend');
A1 = reshape(A,3,[],3);
out = reshape(A1(:,:,ii),3,[]);
or
Ac = mat2cell(A,3,[3 3 3]);
[~,ii] = sort(cellfun(@trace,Ac),'descend');
out = cell2mat(Ac(ii));