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

조회 수: 1 (최근 30일)
Moreno, M.
Moreno, M. 2022년 4월 10일
댓글: Moreno, M. 2022년 4월 11일
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.

채택된 답변

DGM
DGM 2022년 4월 10일
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
Moreno, M.
Moreno, M. 2022년 4월 11일
Hi, thanks for the reply and for the answer. I have just tested it and it works perfectly for arbitrary parameters.
Regards,
Moreno, M.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by