0
votes

How to replace elements of a matrix by an another matrix in MATLAB?

Ex: let say if we have a matrix A, where

A=[1 0 0; 0 1 0; 1 0 1]

I want to replace all ones by

J=[1 0 0; 0 1 0; 0 0 1]

and zeros by

K=[0 0 0; 0 0 0; 0 0 0]

So that I can get 9x9 matrix. So how we will code it in MATLAB

Thanks

2

2 Answers

7
votes

Sounds like you might want to take a look at the kronecker tensor product. This is not a general case but the idea should work for what you want

>> kron(A==1,J)+kron(A==0,K)

ans =

     1     0     0     0     0     0     0     0     0
     0     1     0     0     0     0     0     0     0
     0     0     1     0     0     0     0     0     0
     0     0     0     1     0     0     0     0     0
     0     0     0     0     1     0     0     0     0
     0     0     0     0     0     1     0     0     0
     1     0     0     0     0     0     1     0     0
     0     1     0     0     0     0     0     1     0
     0     0     1     0     0     0     0     0     1

which, for the example case, would simplify to a simpler command:

>> kron(A,J)

ans =

     1     0     0     0     0     0     0     0     0
     0     1     0     0     0     0     0     0     0
     0     0     1     0     0     0     0     0     0
     0     0     0     1     0     0     0     0     0
     0     0     0     0     1     0     0     0     0
     0     0     0     0     0     1     0     0     0
     1     0     0     0     0     0     1     0     0
     0     1     0     0     0     0     0     1     0
     0     0     1     0     0     0     0     0     1
0
votes

You can do:

A2=imresize(A,size(A).*size(J),'nearest');
J2=repmat(J,size(A));
K2=repmat(K,size(A));
A2(A2==1)=J2(A2==1);
A2(A2==0)=K2(A2==0)