MATLAB: How to populate a 2D matrix into a specific Z dimension of a 3D matrix

MATLABmatricesmatrixmatrix manipulation

I have created a 20x3xN 3D matrix (where N is a user defined value passed to a function):
LTM = zeros(20,3,N);
I have also created a 20×3 matrix of values by running a function. This is called 'last20Steps'
What I am trying to do is with a while loop iterate through the Z dimension of the 3D matrix (LTM) and populate the 2D matrix into this with each iteration.
iterationNumber = 1
while iterationNumber <= N
%Function that runs the code to generate the 2D matrix and populate LTM
rndStartState();
iterationNumber = iterationNumber + 1;
end
The outcome should be: LTM(:,:,5) should return the 5th iteration of the 20×3 matrix data.
This is what I have been trying:
LTM(:,:,iterationNumber) = last20Steps;
This returns the following error: Subscripted assignment dimension mismatch.
I have tried not defining the size of the LTM and assigning it as LTM = [] which also does not work.
Any help or advice would be appreciated.
Thanks.

Best Answer

It is not easy to debug code that you describe, rather than actually post. Can you post it, or at least a small distilled example that illustrates the problem?
This works:
A = rand(20,3,10);
B = rand(20,3);
A(:,:,5) = B;
My best guess is that one of your two arrays is somehow not actually the size you expect when you reach that line. You could use set a breakpoint at that line and enter debug mode to see.