How can I define a 3D matrix in MATLAB?
For example a matrix of size (8 x 4 x 20) or add a 3rd dimension to an existing 2D matrix?
Creating Multidimensional Arrays You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.
A 3D matrix is nothing but a collection (or a stack) of many 2D matrices, just like how a 2D matrix is a collection/stack of many 1D vectors. So, matrix multiplication of 3D matrices involves multiple multiplications of 2D matrices, which eventually boils down to a dot product between their row/column vectors.
It can be called a multidimensional array or in some cases a tensor of order 3.
A = zeros(20, 10, 3); %# Creates a 20x10x3 matrix
B = zeros(4,4); C = zeros(size(B,1), size(B,2), 4); %# New matrix with B's size, and 3rd dimension of size 4 C(:,:,1) = B; %# Copy the content of B into C's first set of values
zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0
for a 3D matrix. To confirm the size of your matrices you can run: size(A)
which gives 20 10 3
.
There is no explicit bound on the number of dimensions a matrix may have.
If you want to define a 3D matrix containing all zeros, you write
A = zeros(8,4,20);
All ones uses ones
, all NaN's uses NaN
, all false uses false
instead of zeros
.
If you have an existing 2D matrix, you can assign an element in the "3rd dimension" and the matrix is augmented to contain the new element. All other new matrix elements that have to be added to do that are set to zero.
For example
B = magic(3); %# creates a 3x3 magic square B(2,1,2) = 1; %# and you have a 3x3x2 array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With