Home > Back-end >  Matlab: How to do `repelem` where each element is a matrix?
Matlab: How to do `repelem` where each element is a matrix?

Time:01-15

Suppose I have m-by-n matrices A, B, C arranged in an m-by-n-by-3 tensor P:

P = cat(3, A, B, C);

I now want to make a new tensor where each matrix is repeated K times, making the third dimension size 3K. That is, if K=2 then I want to build the tensor

Q = cat(3, A, A, B, B, C, C);

Is there a nice builtin way to achieve this, or do I need to write a loop for it? Preferably as fast or faster than the manual way.

If A, B, C were scalars I could have used repelem, but it does not work the way I want for matrices. repmat can be used to build

cat(3, A, B, C, A, B, C)

but that is not what I am after either.

CodePudding user response:

As noted by @Cris Luengo, repelem(P, 1, 1, k) will actually do what you want (in spite of what the MATLAB documentation says), but I can think of two other ways to achieve this.

First, you could use repmat to duplicate the tensor k times in the second dimension and then reshape:

Q = reshape(repmat(P, 1, k, 1), m, n, []);

Second, you could use repelem to give you the indices of the third dimension to construct Q from:

Q = P(:, :, repelem(1:size(P,3), k));
  • Related