How to reshape a square matrix diagonally to a vector?

1 回表示 (過去 30 日間)
Sarah A
Sarah A 2019 年 9 月 10 日
編集済み: Stephen23 2019 年 9 月 10 日
Hello,
Suppose that we have the following 3x3 matrix:
A=[
0 1 0
1 1 1
1 1 0];
I need to reshape it to (010111101) where we read the matrix diagonaly from the extreme left of the top row (010) then we repeat this with the upper part (11) then the lower (11) and again from the left diagonal and the upper part is before the lower part (0) then (1) ==> 010111101. please see the attached figure.
So, How can I do that"
Regards,

採用された回答

Stephen23
Stephen23 2019 年 9 月 10 日
>> A = [0,1,0;1,1,1;1,1,0]
A =
0 1 0
1 1 1
1 1 0
>> V = 1:sum(size(A))-1;
>> W = fix(V/2).*(-1).^V;
>> C = arrayfun(@(x)diag(A,x),W, 'uni',0);
>> Z = cat(1,C{:})
Z =
0
1
0
1
1
1
1
0
1
  1 件のコメント
Sarah A
Sarah A 2019 年 9 月 10 日
編集済み: Sarah A 2019 年 9 月 10 日
Thank you. It works with any NxN matrix.

サインインしてコメントする。

その他の回答 (1 件)

Johannes Fischer
Johannes Fischer 2019 年 9 月 10 日
I would start with writing down the subscripts in the order you want to select the elements of the matrix.
A=[0 1 0;
1 1 1;
1 1 0];
row = [1 2 3 1 2 2 3 1 3];
col = [1 2 3 2 3 1 2 3 1];
If you need this for larger matrices I'm sure you'll be able to find an algorithm for NxN matrices
Having these coordinates, you can access the elements via their linear indices.
ind = sub2ind(size(A), row, col);
A(ind)
For a little more on the subject of matrix indexing, read here

カテゴリ

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