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:
copy_2d_to_3d_octave.m
>> 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 0What if we want to copy a 2D matrix slice like
copy_2d_matrix.m
>> B = ones(2, 4)
B =
1 1 1 1
1 1 1 1to 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)orA(:,:,2)orA(:,:,3)
For example, we can copy B to A(:,:,2) using
example.txt
A(:,:,2) = BIn our example with B = ones(2,4) and A = zeros(2,4,3) will look like this:
copy_2d_to_3d_octave.m
>> 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 0Check out similar posts by category:
Octave
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow