MATLAB by Example: Matrices
MATLAB stands for Matrix Laboratory. This example shows how to create, index, and perform operations on matrices.
Code
% Creating a 3x3 matrix
A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
% Accessing elements (row, column)
val = A(2, 3); % 6
% Matrix multiplication
B = eye(3); % Identity matrix
C = A * B;
% Element-wise multiplication
D = A .* 2;
% Transpose
E = A';
% Concatenation
F = [A, B]; % Horizontal
G = [A; B]; % VerticalExplanation
Matrices are the fundamental data type in MATLAB. You can create a matrix by entering elements in square brackets []. Row elements are separated by commas or spaces, and rows are separated by semicolons. For example, [1 2; 3 4] creates a 2x2 matrix. MATLAB also provides functions like zeros, ones, and eye (identity matrix) to quickly generate common matrices.
Indexing in MATLAB is 1-based, meaning the first element is at index 1, not 0. You access elements using parentheses (row, col). You can also use the colon operator : to select entire rows or columns; for instance, A(:, 1) selects all rows in the first column. This slicing capability makes data manipulation extremely efficient.
Matrix operations are intuitive. The asterisk * performs standard linear algebra matrix multiplication. If you want to perform an operation element-by-element (like multiplying every number in a matrix by corresponding numbers in another matrix), you use the dot operator prefix, such as .*, ./, or .^. The single quote ' computes the complex conjugate transpose of a matrix.
Code Breakdown
[1, 2, 3; ...] defines the matrix. Semicolons inside the brackets start a new row.A .* 2 multiplies every element in A by 2. Without the dot, it would try to do matrix multiplication.
