Forming a block diagonal matrix of one certain matrix?

44 ビュー (過去 30 日間)
sn at
sn at 2017 年 2 月 14 日
編集済み: Bruno Luong 2021 年 1 月 30 日
I have a matrix A which is m*n. I want to create a block diagonal matrix of size 100*100 whose diagonal elements are the matrix A.
[A,0,0,0
0,A,0,0
0,0,A,0
0,0,0,A
... ]
function, out = blkdiag(A,A,A,A,...) needs writing down the matrix so many times. Is there any other way to do this (not typing so many matrices as input arguments of blkdiag)?
  2 件のコメント
Teun Burgers
Teun Burgers 2018 年 4 月 18 日
how about
kron(eye(100),A)
or
kron(eye(100),sparse(A))
Rik
Rik 2021 年 1 月 30 日
Comment posted as flag by @Anubhav Halder:
Worked perfectly for me. Thanks.

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

採用された回答

Star Strider
Star Strider 2017 年 2 月 14 日
Cell arrays create comma-separated lists, which are exactly what the blkdiag function wants as its arguments.
See if this does what you want:
A = [1 2; 3 4]; % Original Matrix (Created)
N = 3; % Number Of Times To Repeat
Ar = repmat(A, 1, N); % Repeat Matrix
Ac = mat2cell(Ar, size(A,1), repmat(size(A,2),1,N)); % Create Cell Array Of Orignal Repeated Matrix
Out = blkdiag(Ac{:}) % Desired Result
Out =
1 2 0 0 0 0
3 4 0 0 0 0
0 0 1 2 0 0
0 0 3 4 0 0
0 0 0 0 1 2
0 0 0 0 3 4
  3 件のコメント
Star Strider
Star Strider 2019 年 10 月 24 日
My pleasure!
I appreciate your compliment!
Bruno Luong
Bruno Luong 2021 年 1 月 30 日
編集済み: Bruno Luong 2021 年 1 月 30 日
The MAT2CELL step can be removed
A = [1 2; 3 4];
Ac = repmat({A}, 1, 3);
Out = blkdiag(Ac{:})

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

その他の回答 (2 件)

Teun Burgers
Teun Burgers 2018 年 4 月 19 日

how about:

kron(eye(100),A)

or

kron(eye(100),sparse(A))
  1 件のコメント
Stoyan Margaretov
Stoyan Margaretov 2020 年 6 月 23 日
Genious, that worked perfectly for me!

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


Honglei Chen
Honglei Chen 2017 年 2 月 14 日
eval(sprintf('Out = blkdiag(A%s);',repmat(',A',1,99)))
HTH
  1 件のコメント
Stephen23
Stephen23 2018 年 4 月 18 日
編集済み: Stephen23 2018 年 4 月 18 日
The MATLAB documentation for eval recommends that "Whenever possible, do not include output arguments within the input to the eval function, such as eval(['output = ',expression]). The preferred syntax,"
output = eval(expression)
"allows the MATLAB parser to perform stricter checks on your code, preventing untrapped errors and other unexpected behavior." Because the variable Out does not change this could easily have been achieved in this solution, and thus would follow the advice given in the MATLAB help.
Note that Star Strider's solution avoids all of these problems by simply avoiding eval entirely:

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

カテゴリ

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