Duplicate every element of a matrix to NxN elements
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Xinbing Liu
am 14 Feb. 2019
Kommentiert: Xinbing Liu
am 14 Feb. 2019
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.
0 Kommentare
Akzeptierte Antwort
Stephen23
am 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
Weitere Antworten (1)
KSSV
am 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)
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!