Multidimensional Array in Matlab Programming
Vectorized implementations, execution benchmarks, and step-by-step programming documentation.
MATLAB is built around matrix and array computations. While most daily tasks involve 2D matrices (rows and columns), real-world datasets often require three or more dimensions. Multidimensional arrays extend traditional matrices into 3D, 4D, or higher dimensions, making them essential for tensor algebra, image and video processing, fluid dynamic simulations, and machine learning.
Step 1: Creating Multidimensional Arrays
You can construct a 3D array using the cat() (concatenate) function to stack 2D matrices along a third dimension:
% Concatenate two 2x2 matrices along the 3rd dimension A = cat(3, [1 2; 3 4], [5 6; 7 8]);
disp(A);
% A(:,:,1) accesses the first 2D slice % A(:,:,2) accesses the second 2D sliceAlternatively, preallocate multidimensional arrays using zeros() or ones():
B = zeros(2, 3, 4);
% Creates a 2x3x4 array of zeros C = ones(3, 3, 3);
% Creates a 3x3x3 array of onesStep 2: Accessing Elements
Retrieve specific values by supplying index coordinates for every dimension: (row, column, page/slice):
% Access row 1, column 2, slice 2 elem = A(1, 2, 2);
disp(elem);
% Output: 6Step 3: Modifying Elements and Slices
Update individual values or overwrite entire 2D matrix slices at once:
% Modify a single element at row 2, column 1, slice 1 A(2, 1, 1) = 10;
% Overwrite the entire second slice with a new 2x2 matrix A(:, :, 2) = [9 8; 7 6];Step 4: Array Operations
MATLAB supports element-wise mathematical operations across multidimensional arrays:
D = A + 2;
% Add 2 to every element E = A .* 2;
% Multiply every element by 2Step 5: Inspecting Array Dimensions
Check the total size or the number of dimensions using size() and ndims():
disp(size(A));
% Returns [2 2 2] disp(ndims(A));
% Returns 3 % Get size of a specific dimension (e.g., 3rd dimension) depth = size(A, 3);Step 6: Reshaping Multidimensional Arrays
Reorganize elements into different dimensional structures using reshape(), provided the total element count remains identical:
% Reshape a 2x2x2 array (8 elements) into a 4x2 matrix G = reshape(A, 4, 2);
disp(G);Practical Applications
- Image & Video Processing: RGB color images are stored as 3D arrays
(height × width × 3 color channels); video streams add a 4th dimension for time. - Scientific Simulations: Modeling 3D physical fields like fluid flow, magnetic fields, or thermal distribution over time.
- Machine Learning & AI: High-dimensional tensor computations in deep neural networks.
- Multi-Parameter Testing: Storing experimental data measured across varying temperatures, pressures, and frequencies.
Need Expert Guidance with MATLAB or Simulink?
Our 500+ PhD engineers provide verified MATLAB code, custom Simulink models, and 1-on-1 tutoring with comprehensive code quality verification.