MATLAB - Arrays
MATLAB - Arrays and Data Containers
Section titled “MATLAB - Arrays and Data Containers”The fundamental data structure in MATLAB is the array. Every variable, from a single number (a 1x1 array) to a complex dataset, is stored as a multidimensional array. Understanding how to create, manipulate, and choose the right type of array is key to writing efficient and effective MATLAB code.
Fundamental Array Creation
Section titled “Fundamental Array Creation”MATLAB provides a rich set of functions for creating common types of arrays:
% A 3x4 matrix of all zerosA = zeros(3, 4);
% A 5x5 square matrix of all onesB = ones(5);
% A 4x4 identity matrixI = eye(4);
% A 2x5 matrix of uniformly distributed random numbers between 0 and 1R_uniform = rand(2, 5);
% A 3x3 matrix of normally distributed random numbersR_normal = randn(3);
% A vector with 100 points evenly spaced from 0 to 10V = linspace(0, 10, 100);Multidimensional Arrays
Section titled “Multidimensional Arrays”Arrays can have more than two dimensions. These are often used for image data (height x width x color channels) or for representing data over a 3D grid. You can create them by extending an existing 2D array or by using creation functions with more than two dimension arguments.
% Start with a 2x3 matrix (Page 1)A = [1 2 3; 4 5 6];
% Add a second 'page' to create a 2x3x2 arrayA(:, :, 2) = [7 8 9; 10 11 12];
% Access the element at row 1, col 3, page 2element = A(1, 3, 2); % This will be 9
% Create a 4x3x2 array of random numbers directlyB = rand(4, 3, 2);Essential Array Manipulation Functions
Section titled “Essential Array Manipulation Functions”Instead of a long list, here are some of the most critical functions for working with arrays:
- Size and Shape:
size(A)returns the dimensions of array A.numel(A)returns the total number of elements.length(A)returns the size of the longest dimension. - Reshaping:
reshape(A, new_dims)changes the dimensions of an array without changing its elements. For example,reshape(1:6, 2, 3)creates a 2x3 matrix. - Sorting:
sort(V)sorts a vector. For a matrixM,sort(M, 1)sorts each column, andsort(M, 2)sorts each row. - Finding Elements:
find(A > 5)returns the linear indices of all elements in A that are greater than 5.
Modern Data Containers
Section titled “Modern Data Containers”For more complex or structured data, modern MATLAB offers specialized data containers that are often more efficient and convenient than basic numeric arrays.
String Arrays (Recommended for Text)
Section titled “String Arrays (Recommended for Text)”For handling text, modern MATLAB introduced string arrays, created with double quotes (""). They are more flexible and powerful than traditional character arrays (single quotes '').
% Modern String Array (Recommended)names_str = ["Alice", "Bob", "Charlie"];names_str(2) % Accesses the full string "Bob"
% Old Character Array (Avoid if possible)names_char = ['Alice'; 'Bob '; 'Charlie']; % Requires padding with spaces to be rectangularCell Arrays (For Heterogeneous Data)
Section titled “Cell Arrays (For Heterogeneous Data)”A cell array is a container where each element (a cell) can hold any type of data, including numbers, text, or even other arrays. This is useful for grouping dissimilar data together.
Use parentheses () to index the cells themselves, and curly braces {} to access the content inside a cell.
% Create a 2x3 cell arrayC = {10, 'some text', [1 2; 3 4]; ... @(x) x^2, "a string", {1; 2}};
% Get the cell at (1, 3) (which is a cell containing a matrix)cell_subset = C(1, 3); % Returns a 1x1 cell array
% Get the CONTENT of the cell at (1, 3) (the matrix itself)matrix_content = C{1, 3}; % Returns the 2x2 matrix [1 2; 3 4]Tables (For Tabular Data)
Section titled “Tables (For Tabular Data)”A table is the best choice for storing mixed-type columnar data, like you would find in a spreadsheet or database table. Each column can have a different data type, but all data within a column must be of the same type. Tables are highly recommended for data analysis.
% Create data for the tableLastName = ["Smith"; "Jones"; "Williams"];Age = [38; 29; 45];Smoker = [true; false; true];Height = [71; 69; 64];
% Create the tablepatients = table(LastName, Age, Smoker, Height);disp(patients);
% Access data using dot notation (very convenient)mean_age = mean(patients.Age);fprintf('Mean patient age: %.1f\n', mean_age);
% Access all data for smokerssmoker_data = patients(patients.Smoker, :);disp(smoker_data);