Asked by Benjamin Ong
on 31 Oct 2019

Is there a way I can make each element in a matrix duplicate into a 3 by 3? if

A=[1 0;0 1]

Is there a way i can turn it into

Aew=[1 1 1 0 0 0;1 1 1 0 0 0;1 1 1 0 0 0;0 0 0 1 1 1;0 0 0 1 1 1;0 0 0 1 1 1]

so basically

Anew=repelem(A,3,3)

but without repelem, repmat or any special functions?

Thanks

Answer by Fangjun Jiang
on 31 Oct 2019

Edited by Fangjun Jiang
on 31 Oct 2019

Accepted Answer

a=eye(2);

k=3;

d=blkdiag(ones(k,1),ones(k,1));

b=d*a*d'

%%Or a more generic case

a=[1 2 3;4 5 6];

k=3;

[m,n]=size(a);

d1=ones(k,1)*ones(1,m);

d1=mat2cell(d1,k,ones(1,m));

d1=blkdiag(d1{:});

d2=ones(n,1)*ones(1,k);

d2=mat2cell(d2,ones(n,1),k);

d2=blkdiag(d2{:});

b=d1*a*d2

Answer by Stephen Cobeldick
on 31 Oct 2019

Edited by Stephen Cobeldick
on 31 Oct 2019

>> A = [1,0;0,1]

A =

1 0

0 1

>> V = ceil((1:6)/3);

>> B = A(V,V)

B =

1 1 1 0 0 0

1 1 1 0 0 0

1 1 1 0 0 0

0 0 0 1 1 1

0 0 0 1 1 1

0 0 0 1 1 1

Benjamin Ong
on 1 Nov 2019

This way only seems to produce a 2 by 2 everytime though no matter the size of the initial matrix

Stephen Cobeldick
on 2 Nov 2019

"This way only seems to produce a 2 by 2 everytime though no matter the size of the initial matrix"

Clearly it works, as the example in my answer shows.

Of course it can be trivially adjusted to replicate the elements of any sized array any number of times, to do so requires two very small changes to the V definition:

k = 3;

V = ceil((1:k*size(A,1))/k);

This is certainly a much simpler and more efficient solution than the one that you accepted.

Benjamin Ong
on 2 Nov 2019

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Adam (view profile)

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/488541-duplicate-each-element-in-a-matrix-without-using-repelem-or-repmat#comment_762175

Sign in to comment.