A Matrix is a two-dimensional array of elements. In MATLAB (short for Matrix Laboratory), the matrix is created by assigning the array elements that are delimited by spaces or commas and using semicolons to mark the end of each row.
Creating a Matrix in MATLAB
A matrix can be created by listing elements inside square brackets [ ].
- Elements in a row are separated by spaces or commas (,).
- Rows are separated by semicolons (;).
Syntax:
A = [elements; elements]
Example: Creating a Matrix
% Creating numeric and string matrices
x = [1 2 3; 4 5 6; 7 8 9];
y = ['Geek'; 'Geek'];
Output:
x =
1 2 3
4 5 6
7 8 9
y =
Geeks
Geeks
Finding the Size of a Matrix
You can find the dimensions (rows × columns) of a matrix using the size() function.
Example:
x = [1 2 3 4; 4 5 6 7; 7 8 9 10];
xSize = size(x)
y = ['Geeks'; 'Geeks'];
ySize = size(y)
Output:
xSize =
3 4
ySize =
2 5
Accessing Matrix Elements
To access specific elements, use the syntax:
matrix(row, column)
Example 1: Access a Single Element
x = [1 2 3 4; 4 5 6 7; 7 8 9 10];
x(3,2) % Access element in 3rd row, 2nd column
Output:
ans =
8
Example 2: Accessing Multiple Elements
To access multiple elements:
- x(:, :) -> all rows and columns
- x(1:2, :) -> first two rows
- x(:, 2:end) -> all rows, columns from 2 to end
x = [1 2 3 4; 4 5 6 7; 7 8 9 10];
x(:, :)
x(1:2, :)
x(:, 2:end)
x(1:2, 2:3) % Elements from 2nd to 3rd column in first two rows
Output:
ans =
1 2 3 4
4 5 6 7
7 8 9 10
ans =
1 2 3 4
4 5 6 7
ans =
2 3 4
5 6 7
8 9 10
ans =
2 3
5 6
Adding Elements or Dimensions
You can add rows or columns to a matrix using concatenation ([]) or the cat() function.
Syntax:
cat(dimension, A, B, ...)
- dimension = 1 -> adds rows
- dimension = 2 -> adds columns
Example 1: Using Brackets
x = [1 2 3 4; 4 5 6 7];
y = [7 8 9 10; 11 12 13 14];
a = [x; y]; % Add rows
b = [x; 11 12 13 14]; % Add a new row
x(:,5) = [15; 16]; % Add a column
Output:
a =
1 2 3 4
4 5 6 7
7 8 9 10
11 12 13 14
b =
1 2 3 4
4 5 6 7
11 12 13 14
x =
1 2 3 4 15
4 5 6 7 16
Example 2: Using cat()
x = [1 2 3 4; 4 5 6 7];
y = [1 2 3 4; 4 5 6 7];
a = cat(1, x, y); % Add rows
b = cat(2, x, y); % Add columns
Output:
a =
1 2 3 4
4 5 6 7
1 2 3 4
4 5 6 7
b =
1 2 3 4 1 2 3 4
4 5 6 7 4 5 6 7
Deleting Rows or Columns
You can remove rows or columns by assigning them an empty array [].
Example:
x = [1 2 3 4; 4 5 6 7; 7 8 9 10];
x(3,:) = []; % Delete 3rd row
x(:,3) = []; % Delete 3rd column
Key Points
- MATLAB indices start at 1 (not 0).
- For most operations, matrices must have the same dimensions.
- Use a semicolon (;) at the end of a statement to suppress intermediate outputs.
- In MATLAB, a string is treated as a character array.
- length() gives the total number of elements in a vector, while size() returns matrix dimensions.