Matlab reshape horizontal cat

Hi I want to reshape a matrix but the reshape command doesn't order the elements the way I want it. I have matrix with elements:

A B
C D
E F
G H
I K
L M

and want to reshape it to:

A B E F I K
C D G H L M

So I know how many rows I want to have (in this case 2) and all "groups" of 2 rows should get appended horizontally. Can this be done without a for loop?


You can do it with two reshape and one permute . Let n denote the number of rows per group:

y = reshape(permute(reshape(x.',size(x,2),n,[]),[2 1 3]),n,[]);

Example with 3 columns, n=2 :

>> x = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
x =
     1     2     3
     4     5     6
     7     8     9
    10    11    12
>> y = reshape(permute(reshape(x.',size(x,2),n,[]),[2 1 3]),n,[])
y =
     1     2     3     7     8     9
     4     5     6    10    11    12

Cell array approach -

mat1 = rand(6,2) %// Input matrix
nrows = 3; %// Number of rows in the output

[m,n] = size(mat1);

%// Create a cell array each cell of which is a (nrows x n) block from the input
cell_array1 = mat2cell(mat1,nrows.*ones(1,m/nrows),n);  

%// Horizontally concatenate the double arrays obtained from each cell
out = horzcat(cell_array1{:})

Output on code run -

mat1 =
    0.5133    0.2916
    0.6188    0.6829
    0.5651    0.2413
    0.2083    0.7860
    0.8576    0.3032
    0.1489    0.4494
out =
    0.5133    0.2916    0.5651    0.2413    0.8576    0.3032
    0.6188    0.6829    0.2083    0.7860    0.1489    0.4494
链接地址: http://www.djcxy.com/p/84186.html

上一篇: 使用ode在MATLAB中求解环形激光方程

下一篇: Matlab重塑横向猫