Is there an alternative way to perform the following matrix transformation?

1 回表示 (過去 30 日間)
Erivelton Gualter
Erivelton Gualter 2019 年 11 月 22 日
編集済み: Stephen23 2019 年 11 月 22 日
Is there a better way to perform the following operation.
For example, for the following matrix:
A =
1 13 25
2 14 26
3 15 27
4 16 28
5 17 29
6 18 30
7 19 31
8 20 32
9 21 33
10 22 34
11 23 35
12 24 36
I am looking to transform to:
A_new =
1 13 25 2 14 26 3 15 27
2 14 26 3 15 27 4 16 28
3 15 27 4 16 28 5 17 29
Note, I am combining groups of three rows in a row for the entired matrix.
The following piece of code is already able to perform this. However, I have a huge matrix, and I believe there is an optimal way to do this. Also, I would like to play aroung with the number of rows to create the new matrix.
% Matrix A
A=1:36; A = reshape(A,12,3)
j=1;
for i=1:3
A_new(i,:) = [A(j,:) A(j+1,:) A(j+2,:)];
j = j +1;
end
A_new

採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 11 月 22 日
編集済み: Andrei Bobrov 2019 年 11 月 22 日
i = 3;
[m,n] = size(A);
j = hankel(1:i,i:m);
out = A(sub2ind([m,n],kron(j,ones(1,n)),repmat(1:n,i,m-n+1)));
or in your case
j = hankel(1:i,i:2*i-1);
out = A(sub2ind([m,n],kron(j,ones(1,i)),repmat(1:n,i,i)));
or for out:
out = reshape(permute(reshape(A(j,:),i,n,[]),[1,3,2]),i,[]);

その他の回答 (1 件)

Stephen23
Stephen23 2019 年 11 月 22 日
編集済み: Stephen23 2019 年 11 月 22 日
>> N = 3;
>> [R,C] = size(A); % specify R to change the number of rows of A used.
>> X = hankel(1:N,N:R);
>> B = reshape(A(X,:).',N*C,[]).'
B =
1 13 25 2 14 26 3 15 27
2 14 26 3 15 27 4 16 28
3 15 27 4 16 28 5 17 29
4 16 28 5 17 29 6 18 30
5 17 29 6 18 30 7 19 31
6 18 30 7 19 31 8 20 32
7 19 31 8 20 32 9 21 33
8 20 32 9 21 33 10 22 34
9 21 33 10 22 34 11 23 35
10 22 34 11 23 35 12 24 36

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by