How to copy a 2D matrix to a slice of a 3D matrix in Octave

In our previous post we showed how to create a 3D matrix in Octave, for example this 2x4x3 matrix:

>> A = zeros(2, 4, 3);
>> A
A =

ans(:,:,1) =

   0   0   0   0
   0   0   0   0

ans(:,:,2) =

   0   0   0   0
   0   0   0   0

ans(:,:,3) =

   0   0   0   0
   0   0   0   0

What if we want to copy a 2D matrix slice like

>> B = ones(2, 4)
B =

   1   1   1   1
   1   1   1   1

to the 3D matrix?

First, we need to think about which matrix indices we need to copy to.
Obviously, since B is a 2x4 matrix and A is a 2x4x3 matrix, the third dimension needs to be fixed since the size of the first and second dimension of A is identical to the dimension of B.

Hence we can copy B to either

  • A(:,:,1) or
  • A(:,:,2) or
  • A(:,:,3)

For example, we can copy B to A(:,:,2) using

A(:,:,2) = B

In our example with B = ones(2,4) and A = zeros(2,4,3) will look like this:

>> A(:,:,2) = B
A =

ans(:,:,1) =

   0   0   0   0
   0   0   0   0

ans(:,:,2) =

   1   1   1   1
   1   1   1   1

ans(:,:,3) =

   0   0   0   0
   0   0   0   0