How to create a 2D diagonal matrix from a 3D matrix with a generic dimension? It could be with a loop structure.

4 ビュー (過去 30 日間)
%%3D matrix k
n=3;
k=zeros(n)
for a=1:n
for b=1:n
for c=1:n
k(b,c,a)=c;
end
end
end
using blkdiag could be obtained, however for a generic number of matrices n, this doesn't work.
u=blkdiag(k(:,:,1),k(:,:,2),k(:,:,3))
  1 件のコメント
Stephen23
Stephen23 2017 年 11 月 16 日
What is the expected output? Can you please provide a specific example with input and output arrays.

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

採用された回答

KL
KL 2017 年 11 月 16 日
Use a cell array and then something like,
c = arrayfun(@(x) k(:,:,x),1:n,'uni',0)
u = blkdiag(c{:})
u =
1 2 3 0 0 0 0 0 0
1 2 3 0 0 0 0 0 0
1 2 3 0 0 0 0 0 0
0 0 0 1 2 3 0 0 0
0 0 0 1 2 3 0 0 0
0 0 0 1 2 3 0 0 0
0 0 0 0 0 0 1 2 3
0 0 0 0 0 0 1 2 3
0 0 0 0 0 0 1 2 3

その他の回答 (1 件)

Matt J
Matt J 2017 年 11 月 16 日
kcell=num2cell(k,[1,2]);
u=blkdiag(kcell{:});

カテゴリ

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