How to Create Matrix in MATLAB: Syntax and Examples
In MATLAB, you create a matrix by enclosing numbers in square brackets
[] with spaces or commas separating columns and semicolons separating rows. For example, A = [1 2 3; 4 5 6] creates a 2x3 matrix.Syntax
To create a matrix in MATLAB, use square brackets []. Separate elements in the same row with spaces or commas, and separate rows with semicolons.
- Square brackets []: Define the matrix.
- Spaces or commas: Separate columns.
- Semicolons: Separate rows.
matlab
A = [1 2 3; 4 5 6]
Output
[
1 2 3
4 5 6
]
Example
This example creates a 3x3 matrix with numbers from 1 to 9 arranged in rows.
matlab
M = [1 2 3; 4 5 6; 7 8 9] disp(M)
Output
[
1 2 3
4 5 6
7 8 9
]
Common Pitfalls
Common mistakes when creating matrices include:
- Using commas and semicolons incorrectly (commas separate columns, semicolons separate rows).
- Mixing row lengths, which causes errors because all rows must have the same number of columns.
- Forgetting square brackets, which leads to syntax errors.
matlab
Wrong: B = [1 2; 3 4 5] % Rows have different lengths Right: B = [1 2 0; 3 4 5] % Rows have equal length
Output
Error using [ ]
Dimensions of matrices being concatenated are not consistent.
B =
1 2 0
3 4 5
Quick Reference
| Syntax | Description |
|---|---|
| [a b c] | Row vector with elements a, b, c |
| [a; b; c] | Column vector with elements a, b, c |
| [1 2; 3 4] | 2x2 matrix with rows [1 2] and [3 4] |
| zeros(m,n) | m-by-n matrix of zeros |
| ones(m,n) | m-by-n matrix of ones |
| eye(n) | n-by-n identity matrix |
Key Takeaways
Use square brackets [] with spaces or commas for columns and semicolons for rows to create matrices.
All rows in a matrix must have the same number of elements.
Common errors come from inconsistent row lengths or missing brackets.
MATLAB also provides functions like zeros, ones, and eye to create special matrices quickly.
Display matrices using disp or just typing the variable name.