How to stack k copies of a matrix

3 views (last 30 days)
Gautam Goel
Gautam Goel on 2 Feb 2021
Commented: Walter Roberson on 3 Feb 2021
I would like to write a function which takes an integer k > 0 as input and a m by n matrix A as input and produces a m by n by k matrix such that each m by n slice is equal to A; this operation is sometimes colloquially referred to as "stacking" copies of A. It is easy to do this using for loops; we first initialize a m by n by k matrix of zeros and then iterate over the last dimension, setting each slice to be equal to A. Is there an easier way? It seems like Matlab should have built-in functions for this.

Answers (2)

David Hill
David Hill on 3 Feb 2021
a=reshape(repmat(A(:),k,1),[size(A),k]);

James Tursa
James Tursa on 3 Feb 2021
B = repmat(A,1,1,k);
  3 Comments
James Tursa
James Tursa on 3 Feb 2021
I think you meant B = A(:,:,ones(1,k))
Walter Roberson
Walter Roberson on 3 Feb 2021
Ah, yes, you are right ;-)

Sign in to comment.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!