Putting one matrix a varying number of times along the diagonal of another matrix

5 visualizaciones (últimos 30 días)
I have a matrix A which is 6x6. I need to create another matrix where A is along the diagonal with the other entries being 0. I know I could use blkdiag() for this, but the issue is I need to have as many entries of A as the value of another variable that appears earlier in the code. Let's call it n. Sometimes n could be 2, so the matrix would be a 12x12 with A along the diagonal. Sometimes n could be 100 so the ouput matrix would be 600x600 since A needs to appear 100 times. How could I go about automating this process so I don't have to write blkdiag(A,A,A,A...)? Thanks!

Respuesta aceptada

John D'Errico
John D'Errico el 23 de Jun. de 2022
A = rand(3);
n = 50;
Acell = repmat({sparse(A)},[1,n]);
B = blkdiag(Acell{:});
spy(B)
Note that I made A sparse in there, so that the final resulting matrix will also be sparse.
  4 comentarios
Steven Lord
Steven Lord el 23 de Jun. de 2022
M = magic(3)
M = 3×3
8 1 6 3 5 7 4 9 2
N = 4;
C = repmat({M}, 1, N)
C = 1×4 cell array
{3×3 double} {3×3 double} {3×3 double} {3×3 double}
B = blkdiag(C{:}) % Equivalent to blkdiag(M, M, M, M)
B = 12×12
8 1 6 0 0 0 0 0 0 0 0 0 3 5 7 0 0 0 0 0 0 0 0 0 4 9 2 0 0 0 0 0 0 0 0 0 0 0 0 8 1 6 0 0 0 0 0 0 0 0 0 3 5 7 0 0 0 0 0 0 0 0 0 4 9 2 0 0 0 0 0 0 0 0 0 0 0 0 8 1 6 0 0 0 0 0 0 0 0 0 3 5 7 0 0 0 0 0 0 0 0 0 4 9 2 0 0 0 0 0 0 0 0 0 0 0 0 8 1 6
Search the documentation for "comma-separated list" for an explanation of how that last line works.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Operating on Diagonal Matrices en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by