# How to rotate matrix? [closed]

Consider the matrix 'm1' :

m1 = RandomReal[{0, 1}, {100, 100}];


The question is, how to rotate the 'm1' data 45 degrees and extract the matrix 'm2' from it (shown in the fig. below) ?:

• One can observe that m2 has dimensions $50\times50$. Therefore, m2=m1[[26;;75,26;;75]]. I have to add that you do not provide all the details, is the rotation clock wise in both cases? Commented Feb 5, 2022 at 7:44
• In the first step, the 'm1' matrix data should be rotated e.g. 45 degrees to the right and then the 'm2' matrix should be extracted. Commented Feb 5, 2022 at 8:26
• How would m2 look like for the numeric array m1 = Partition[Range[16],4]?
– kglr
Commented Feb 5, 2022 at 8:44
• @kglr. Such a matrix has too small dimension. Commented Feb 5, 2022 at 8:53
• I guess it's not possible :( Commented Feb 5, 2022 at 9:01

Perhaps something like

ClearAll[dM, dMValues, labeledMatrixPlot, rotatedMatrixPlot]

dM[mat_] := (DiamondMatrix[All, Dimensions @ mat] /. 0 -> "") mat /. Times["", _] -> ""

dMValues[mat_] := Values @ KeySort @
GroupBy[SparseArray[DiamondMatrix[All, Dimensions @ mat]][
"NonzeroPositions"], -Total @ # &, Extract[mat, Reverse @ #] &]

labeledMatrixPlot = MatrixPlot[#, ##2,
ImageSize -> 1 -> 40, Mesh -> All,
ColorRules -> "" -> White,
FrameTicks -> {{#, #}, {#, #}} & @ Range[Length @ #],
Epilog -> MapIndexed[Text[Style[#, Small], Reverse @ #2 - .5] &, #, {2}]] &;

rotatedMatrixPlot[mp_] := Show[MapAt[GeometricTransformation[#,
RotationTransform[Pi/4, Mean /@ PlotRange[mp]]] &, mp, {1}] /.
Text[a_, pos_] :>
Text[a, RotationTransform[Pi/4, {n/2, n/2}] @ pos], Frame -> False]


Examples:

n = 7;

SeedRandom[1]

m1 = Round[RandomReal[{0, 1}, {n, n}], .01];

Multicolumn[{labeledMatrixPlot[m1],
labeledMatrixPlot[dM @ m1],
rotatedMatrixPlot[labeledMatrixPlot[dM @ m1]],
dMValues @ m1 // Grid // Style[#, 24] &},
2, Appearance -> "Horizontal", Alignment -> Center]


Use n = 8 above to get

• Thanks. It's close now. The last result is not a matrix, i.e. has a number of columns / rows 5 and 6. But that's easy to reduce to a 5x5 matrix. Commented Feb 5, 2022 at 15:21
• How to obtain the data from the last figure (only those in colored boxes) as a list? Commented Feb 5, 2022 at 19:09
• @ralph, please see the update.
– kglr
Commented Feb 6, 2022 at 0:25