How to dynamically change a matrix by block?

Say I have A = [1:8; 11:18; 21:28; 31:38; 41:48]Now I would like to move everything from column 4 forward to the row position. How to achieve this?

A =
     1     2     3     4     5     6     7     8
    11    12    13    14    15    16    17    18
    21    22    23    24    25    26    27    28
    31    32    33    34    35    36    37    38
    41    42    43    44    45    46    47    48

to

A2 =

     1     2     3     4    
    11    12    13    14    
    21    22    23    24    
    31    32    33    34    
    41    42    43    44    
     5     6     7     8
    15    16    17    18
    35    36    37    38
    45    46    47    48

reshapedoesn't seem to do the trick

+2
source share
3 answers

Here is a vectorial approach with reshapeand permute-

reshape(permute(reshape(a,size(a,1),4,[]),[1,3,2]),[],4)

Run Example -

>> a
a =
    20    79    18    82    27    23    59    66    46    21    48    95
    96    83    46    49    34    88    23    42    17    27    15    54
    11    88    34    92    23    62    86    56    32    32    91    54
>> reshape(permute(reshape(a,size(a,1),4,[]),[1,3,2]),[],4)
ans =
    20    79    18    82
    96    83    46    49
    11    88    34    92
    27    23    59    66
    34    88    23    42
    23    62    86    56
    46    21    48    95
    17    27    15    54
    32    32    91    54
+6
source

Use Matrix Indexing !

B=[A(:,1:4);A(:,5:8)]

In a loop ...

for ii=0:floor(size(A,2)/4)-1
   B([1+5*ii:5*(ii+1)],:)=A(:,[1+4*ii:4*(ii+1)] );
end
+3
source

... , , -, , :

B = cell2mat(mat2cell(A, size(A, 1), 4 * ones((size(A, 2) / 4), 1)).');

mat2cell, . , A, 4, size(A, 2) / 4. , , 4, size(A, 2) / 4 , . , cell2mat.

+2

Source: https://habr.com/ru/post/1660284/


All Articles