问题
Given the matrix I = [1,2;3,4]
, I would like to duplicate the elements to create a matrix I2
such that:
I2 = [1 1 1 2 2 2
1 1 1 2 2 2
1 1 1 2 2 2
3 3 3 4 4 4
3 3 3 4 4 4
3 3 3 4 4 4]
Other than using repmat
, what other methods or functions are available?
回答1:
Use kron:
>> N = 3 %// Number of times to replicate a number in each dimension
>> I = [1,2;3,4];
>> kron(I, ones(N))
ans =
1 1 1 2 2 2
1 1 1 2 2 2
1 1 1 2 2 2
3 3 3 4 4 4
3 3 3 4 4 4
3 3 3 4 4 4
This probably deserves some explanation in case you're not aware of what kron
does. kron
stands for the Kronecker Tensor Product. kron
between two matrices A
of size m x n
and B
of size p x q
creates an output matrix of size mp x nq
such that:

Therefore, for each coefficient in A
, we take this value, multiply it with every value in the matrix B
and we position these matrices in the same order as we see in A
. As such, if we let A = I
, and B
be the 3 x 3 matrix full of ones, you thus get the above result.
回答2:
Using indexing:
I = [1, 2; 3, 4]; %// original matrix
n = 3; %// repetition factor
I2 = I(ceil(1/n:1/n:size(I,1)), ceil(1/n:1/n:size(I,2))); %// result
回答3:
One-liner with bsxfun -
R = 3; %// Number of replications
I2 = reshape(bsxfun(@plus,permute(I,[3 1 4 2]),zeros(R,1,R)),R*size(I,1),[])
Sample run -
I =
3 2 5
9 8 9
I2 =
3 3 3 2 2 2 5 5 5
3 3 3 2 2 2 5 5 5
3 3 3 2 2 2 5 5 5
9 9 9 8 8 8 9 9 9
9 9 9 8 8 8 9 9 9
9 9 9 8 8 8 9 9 9
来源:https://stackoverflow.com/questions/28847890/how-to-duplicate-elements-of-a-matrix-without-using-the-repmat-function