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 Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by