ali eskandari
ali eskandari

Reputation: 75

how to insert a matrix within another matrix in matlab

We have a data set X n*m matrix and I want to create a matrix like this W=[0 X;X' 0] how should I do that in Matlab?

   A=[1 2;3 4];
   B=[0 A;A' 0];

what's wrong with that code?

Upvotes: 1

Views: 462

Answers (3)

OmG
OmG

Reputation: 18838

Because the size of 0 is not the as A and A' in row and column. You can create a matrix with the size of what you want:

B = zeros(2*size(A));

and replace the value where you want:

B(1:2, 3:4) = A;
B(3:4, 1:2) = A.';

Upvotes: 0

Wolfie
Wolfie

Reputation: 30047

You just need to use zeros to make sure the dimensions agree

A = [1 2; 3 4];
z = zeros( size( A ) );
B = [ z, A; A', z ];

Upvotes: 1

rahnema1
rahnema1

Reputation: 15837

A possible solution using kron:

A = [1 2; 3 4]

result = kron([0 1;0 0], A) + kron([0 0;1 0], A');

result =

   0   0   1   2
   0   0   3   4
   1   3   0   0
   2   4   0   0

Upvotes: 2

Related Questions