MATLAB - Matrix
MATLAB - Matrices and Arrays
Section titled “MATLAB - Matrices and Arrays”In MATLAB, the fundamental data type is the array. A matrix is simply a two-dimensional array, but MATLAB’s capabilities extend to arrays with any number of dimensions. Understanding how to create, manipulate, and access array data is the most critical skill for any MATLAB user.
Creating Matrices and Arrays
Section titled “Creating Matrices and Arrays”You can create a matrix by entering elements in each row, separated by commas or spaces, and using a semicolon (;) to mark the end of each row. All elements are enclosed in square brackets [].
For example, let’s create a 4-by-5 matrix A:
% The semicolon at the end of the line suppresses the output.A = [1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
% To display the matrix, just type its name:AMATLAB will execute the above statement and return the following result:
A =
1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8Using Built-in Functions for Array Creation
Section titled “Using Built-in Functions for Array Creation”Manually creating large matrices is tedious. MATLAB provides functions to generate common types of matrices:
% Create a 3x3 matrix of all zerosZ = zeros(3, 3);
% Create a 2x4 matrix of all onesO = ones(2, 4);
% Create a 4x4 identity matrix (ones on the diagonal)I = eye(4);
% Create a 3x5 matrix of uniformly distributed random numbersR = rand(3, 5);
% Create a 3x5 matrix of normally distributed random numbersN = randn(3, 5);Indexing: Accessing Array Elements
Section titled “Indexing: Accessing Array Elements”Indexing is the way you select specific elements from an array. MATLAB is a 1-based indexing language, meaning the first element is at index 1, not 0.
Subscript Indexing (Row, Column)
Section titled “Subscript Indexing (Row, Column)”To reference an element in the m-th row and n-th column of a matrix A, you use the syntax A(m, n).
% Let's use the matrix A from beforeA = [1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
% Get the element in the 2nd row, 5th columnelement = A(2, 5)MATLAB will return:
element = 6Slicing with the Colon Operator (:)
Section titled “Slicing with the Colon Operator (:)”The colon operator : is extremely powerful. It can be used to select entire rows, columns, or ranges.
% Get all elements in the 4th columncol_4 = A(:, 4);
% Get all elements in the 3rd rowrow_3 = A(3, :);
% Get a submatrix from rows 2-3 and columns 2-4submatrix = A(2:3, 2:4);
% Get all elements from the 3rd column to the endlast_cols = A(:, 3:end); % 'end' is a keyword for the last indexThe submatrix example will produce:
submatrix =
3 4 5 4 5 6Logical Indexing (The Modern Way)
Section titled “Logical Indexing (The Modern Way)”Logical indexing is a highly efficient and readable technique. You create a logical array (containing true and false values) of the same size as your data and use it to select elements where the index is true.
% Find all elements in matrix A that are greater than 5large_values = A(A > 5)
% This returns a column vector of the values that satisfy the condition.
% You can also use it to modify values% Replace all odd numbers with 0A_modified = A;% rem(A, 2) == 1 creates a logical mask for odd numbersA_modified(rem(A_modified, 2) == 1) = 0;Modifying Matrices
Section titled “Modifying Matrices”Deleting a Row or a Column
Section titled “Deleting a Row or a Column”You can delete an entire row or column by assigning an empty array [] to it.
% Create a fresh copy of the matrixA_temp = [1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
% Delete the 4th rowA_temp(4, :) = [];
% Now A_temp is a 3x5 matrix.
% Delete the 5th columnA_temp(:, 5) = [];
% Now A_temp is a 3x4 matrix.Example: Concatenating and Reshaping
Section titled “Example: Concatenating and Reshaping”You can build larger matrices by concatenating smaller ones. Let’s create a 4-by-3 matrix by duplicating and stacking the second and third rows of an existing matrix.
% Original 3x3 matrixa = [1 2 3; 4 5 6; 7 8 9];
% We want rows 2 and 3, then rows 2 and 3 again% Create a vector of the row indices we wantindex_vector = [2, 3, 2, 3];
% Use this vector to create the new matrixnew_mat = a(index_vector, :)The result is a new matrix constructed in the specified order:
new_mat =
4 5 6 7 8 9 4 5 6 7 8 9Core Matrix Operations
Section titled “Core Matrix Operations”Here’s a brief overview of essential matrix operations. A critical concept is the difference between matrix operations (which follow the rules of linear algebra) and element-wise operations (which apply an operation to each element independently).
- Addition and Subtraction (
+,-): These are always element-wise. The matrices must have the same dimensions.C = A + B - Matrix Multiplication (
*): Follows linear algebra rules. The number of columns in the first matrix must equal the number of rows in the second.C = A * B - Element-wise Multiplication (
.*): Multiplies corresponding elements. The matrices must have the same dimensions.C = A .* B - Matrix Division (
\,/): Solves systems of linear equations.x = A\bis a more robust way of solvingA*x = b. - Element-wise Division (
./): Divides corresponding elements.C = A ./ B - Transpose (
'): Flips the matrix over its diagonal.B = A' - Determinant (
det): A scalar value computed from a square matrix.d = det(A) - Inverse (
inv): For a square matrixA, its inverseBis such thatA*Bis the identity matrix.B = inv(A). Note: Usinginvis often less accurate and slower than using the backslash operator (\) for solving equations.
Best Practices & Further Learning
Section titled “Best Practices & Further Learning”Pre-allocation: If you know the final size of a matrix you’re building in a loop, pre-allocate it with zeros() or ones() before the loop. This is significantly faster than growing the array in each iteration.
Modern Data Structures: For mixed data (numbers, text, categories), consider using table or timetable objects. They provide named columns and are more flexible than purely numeric matrices for data analysis tasks.