Matlab changes the horizontal cat

Hi, I want to change the matrix, but the reshape command does not arrange the elements the way I want them. I have a matrix with elements:

AB CD EF GH IK LM 

and want to change it to:

 ABEFIK CDGHLM 

So, I know how many lines I want to have (in this case 2), and all the โ€œgroupsโ€ of 2 lines should be added horizontally. Can this be done without a for loop?

+6
source share
2 answers

You can do this with two reshape and one permute . Let n denote the number of rows in a group:

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

Three-column example, 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 
+4
source

Cellular array -

 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 xn) 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{:}) 

The result of code execution is

 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 
+1
source

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


All Articles