Duplicate every element of a matrix to NxN elements

1 view (last 30 days)
Hello, I need to duplicate all the elements of an MxM matrix to NxN elements so the resulting matrix has the size (M*N)x(MxN). For example,
A =
1 2
3 4
I want the matrix B to be duplicated from A's elements such that
B =
1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4
I have been using the following loops to accomplish this:
for k = 1:M
for j =1:M
B((j-1)*N+1 : j*N, (k-1)*N+1 : k*N) = A(j,k);
end
end
My question is: is there a more efficient way of doing it? If M and N are not large, it's not a big deal. But when they are large, the nested loop can take quite a long time.

Accepted Answer

Stephen23
Stephen23 on 14 Feb 2019
>> M = [1,2;3,4];
>> kron(M,[1,1;1,1])
ans =
1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4

More Answers (1)

KSSV
KSSV on 14 Feb 2019
A = [1 2
3 4 ] ;
[nx,ny] = size(A) ;
B = cell(nx,ny) ;
for i = 1:nx
for j = 1:ny
B{i,j} = repelem(A(i,j),nx,ny) ;
end
end
B = cell2mat(B)

Categories

Find more on MATLAB in Help Center and File Exchange

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!