Multidimensional arrays are powerful data structures in MATLAB that extend beyond the familiar 2D matrices. They allow you to represent and manipulate data in three or more dimensions, making them invaluable for complex scientific computations, image processing, and data analysis tasks.
In MATLAB, you can create multidimensional arrays using various methods. The simplest approach is to use the zeros
, ones
, or rand
functions with multiple dimension arguments.
% Create a 3x4x2 array of zeros
A = zeros(3, 4, 2);
% Create a 2x3x4x5 array of random numbers
B = rand(2, 3, 4, 5);
Alternatively, you can construct multidimensional arrays by concatenating lower-dimensional arrays:
% Create two 3x3 matrices
M1 = [1 2 3; 4 5 6; 7 8 9];
M2 = [10 11 12; 13 14 15; 16 17 18];
% Concatenate them into a 3x3x2 array
C = cat(3, M1, M2);
Accessing elements in multidimensional arrays is similar to MATLAB Matrix Indexing, but with additional indices for each dimension:
% Access the element at row 2, column 3, depth 1
element = C(2, 3, 1);
% Assign a value to a specific element
C(1, 1, 2) = 100;
% Extract a 2D slice from the 3D array
slice = C(:, :, 1);
Many MATLAB Array Operations work seamlessly with multidimensional arrays. For example, element-wise operations and mathematical functions can be applied directly:
% Element-wise multiplication
D = A .* B;
% Apply a function to all elements
E = sin(C);
MATLAB provides functions to change the dimensions of arrays while preserving their data:
reshape
: Changes the dimensions of an array without altering its datasqueeze
: Removes singleton dimensions (dimensions with size 1)permute
: Rearranges the dimensions of an array% Reshape a 3x4x2 array into a 4x3x2 array
F = reshape(A, 4, 3, 2);
% Remove singleton dimensions
G = squeeze(rand(3, 1, 4, 1));
% Permute dimensions
H = permute(C, [2, 3, 1]);
Multidimensional arrays are extensively used in various fields:
Mastering multidimensional arrays in MATLAB opens up a world of possibilities for complex data manipulation and analysis. As you become more comfortable with these structures, you'll find them indispensable in your MATLAB programming toolkit.