Does anyone know an efficient way of replicating a matrix in a predetermined pattern(such as diagonal or triangular)?
Some examples: 1. We have A=[1,2;3,4] and we want B=[A,zeros(2);zeros(2),A] 2. We have A=[1,2;3,4] and we want B=[A,zeros(2);A,A] 3. We have a=[1;2;3;4] and we want B=[a,zeros(4,1);zeros(4,1),a]

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 20 Jan. 2012

3 Stimmen

  1. kron([1 0;0 1],A)
  2. kron([1 0;1 0],A)
  3. kron([1 0 0;0 0 1],A)
That is, put a 1 for each copy of A that should appear, and put a 0 for each place 0's the same size as A should appear.

6 Kommentare

Andrew Newell
Andrew Newell am 21 Jan. 2012
Wow! I wish I could vote for this one twice!
Andrew Newell
Andrew Newell am 21 Jan. 2012
However, I think 2 and 3 should be
kron([1 0; 1 1],A)
kron([1 0; 1 0],A)
Mohammad Tabesh
Mohammad Tabesh am 21 Jan. 2012
Just Awesome!
Walter Roberson
Walter Roberson am 21 Jan. 2012
2 should be [1 0;1 1], but for #3 notice that Mohammad wanted 4 zeros rather than 2.
Andrew Newell
Andrew Newell am 21 Jan. 2012
Right, but lowercase a is a 4 x 1 vector.
Walter Roberson
Walter Roberson am 21 Jan. 2012
Ah, I missed that different variables were being used.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Andrew Newell
Andrew Newell am 20 Jan. 2012

0 Stimmen

For 1. you could use
B = blkdiag(A,A);
For 2, why not just use the command you gave?
B=[A,zeros(2);A,A] ;
For 3:
B=[a' zeros(1,4); zeros(1,4) a']'
EDIT: Here is a generalization of 1:
n = 3; % e.g.
Amat = repmat(A,n,1);
Acell = mat2cell(Amat,2*ones(1,n),2);
B = blkdiag(Acell{:})

1 Kommentar

Mohammad Tabesh
Mohammad Tabesh am 20 Jan. 2012
Thanks for the answer but the point is that I don't want to hard code the number of times I need to replicate the A matrix (Imagine that I need 10 replications of A for example 2)

Melden Sie sich an, um zu kommentieren.

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by