Reshape a 'column' matrix into a 'row' matrix

3 views (last 30 days)
Hi, I hope you are well.
I have a matrix 'X' that is generated through a series of parameters, that in the end of the day is a column-wise concatenated matrix such as:
X = [A; B; C; ...; P], where A, B, C, ..., P are 'p' equally-sized [m - 1, q] matrices.
My goal is to reshape this matrix in a way that the new matrix 'X' is:
X = [A, B, C, ..., P]
Ideally, this would be done without loops or manually, so that the operation could be vectorised. A representative example to solve 'similar' to my case matrix would be:
m = 8;
p = 2;
q = 10;
X = rand(p * (m - 1), q);
X(:, [1, q]) = 0;
Which would be a random matrix made of 2 (p) submatrices of [7, 10] ([m - 1, q]) elements. The final solution that I am seeking would be, for this particular case:
Y = [X(1 : m - 1, :), X(m : 2 * (m - 1), :)];
Some help on how to do this transformation for a generic number of matrices 'p' of dimension [m - 1, q] via the reshape command, circshift, rot90, transpose or similar would be greatly appreciated, so that the transformation was compact.
Thanks in advance and regards,
Moreno, M.

Accepted Answer

DGM
DGM on 10 Apr 2022
There are other ways this could be done, but just using reshape() and permute() is often the fastest:
m = 5;
p = 2;
q = 5;
X = rand(p * (m - 1), q);
X(:, [1, q]) = 0
X = 8×5
0 0.4353 0.6008 0.1466 0 0 0.9317 0.9804 0.1811 0 0 0.9719 0.7923 0.6327 0 0 0.3685 0.4549 0.4899 0 0 0.9231 0.8038 0.1596 0 0 0.3666 0.9581 0.8240 0 0 0.8689 0.9033 0.3245 0 0 0.3822 0.8846 0.7878 0
% given example
Y = [X(1 : m - 1, :), X(m : 2 * (m - 1), :)]
Y = 4×10
0 0.4353 0.6008 0.1466 0 0 0.9231 0.8038 0.1596 0 0 0.9317 0.9804 0.1811 0 0 0.3666 0.9581 0.8240 0 0 0.9719 0.7923 0.6327 0 0 0.8689 0.9033 0.3245 0 0 0.3685 0.4549 0.4899 0 0 0.3822 0.8846 0.7878 0
% using reshape()
Y = reshape(permute(reshape(X.',q,m-1,p),[1 3 2]),[],m-1).'
Y = 4×10
0 0.4353 0.6008 0.1466 0 0 0.9231 0.8038 0.1596 0 0 0.9317 0.9804 0.1811 0 0 0.3666 0.9581 0.8240 0 0 0.9719 0.7923 0.6327 0 0 0.8689 0.9033 0.3245 0 0 0.3685 0.4549 0.4899 0 0 0.3822 0.8846 0.7878 0
  1 Comment
Moreno, M.
Moreno, M. on 11 Apr 2022
Hi, thanks for the reply and for the answer. I have just tested it and it works perfectly for arbitrary parameters.
Regards,
Moreno, M.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!