Reshaping a 2D matrix into a 3D matrix (layers of square matrices) with specific order (no loop)
조회 수: 2 (최근 30일)
이전 댓글 표시
I have a 15 x 15 matrix(2D) (which is made of 9 blocks (3 x 3) of 5 x 5 matrices). I would like to reshape this matrix into a 3x3 x 25 matrix(3D); however the matrix elements of each 3x3 layer are chosen in a specific order from the original 2D matrix. The ordering is described below.
The elements of the 25 matrices are chosen from the elements of 5 x 5 matrices embedded in the original 2D matrix. I would like not to utilize "for" loops because the code becomes very inefficient as the dimensions of the original matrix grows. I have used the following code to reshape the 2D matrix, but this piece of code scrambles the rows and columns, and the order of 25 layers is not deterministic.
A =[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
4 8 13 19 26 34 43 53 64 76 89 103 118 134 151
7 12 18 25 33 42 52 63 75 88 102 117 133 150 168
11 17 24 32 41 51 62 74 87 101 116 132 149 167 186
16 23 31 40 50 61 73 86 100 115 131 148 166 185 205
22 30 39 49 60 72 85 99 114 130 147 165 184 204 225
29 38 48 59 71 84 98 113 129 146 164 183 203 224 246
37 47 58 70 83 97 112 128 145 163 182 202 223 245 268
46 57 69 82 96 111 127 144 162 181 201 222 244 267 291
56 68 81 95 110 126 143 161 180 200 221 243 266 290 315
67 80 94 109 125 142 160 179 199 220 242 265 289 314 340];
permute(reshape(A', 25, 3, 3), [3 2 1])
This scheme, if figured out, helps calculating the determinant of 3 x 3 blocks inside very large 3N x 3M (or 3N x 3N) matrices.
Thanks
댓글 수: 0
채택된 답변
Andrei Bobrov
2017년 9월 20일
편집: Andrei Bobrov
2017년 9월 20일
B = mat2cell(A,[5 5 5],[5 5 5]);
C = cat(3,B{:});
out = reshape(permute(C(1,1:3,:),[3 2 1]),3,[]);
or
[m,n] = size(A);
q = 3;
out = reshape(A((1:5:m)'+(0:5:n-1)*m + reshape(m*(0:q-1),1,1,[])),q,[]);
댓글 수: 0
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!