How to Create Array in MATLAB: Syntax and Examples
In MATLAB, you create an array by enclosing elements in square brackets
[]. Separate elements in a row with spaces or commas, and separate rows with semicolons. For example, A = [1 2 3; 4 5 6] creates a 2x3 array.Syntax
To create an array in MATLAB, use square brackets []. Inside, list elements separated by spaces or commas for columns, and use semicolons to separate rows.
- Row elements: separated by spaces or commas
- Rows: separated by semicolons
matlab
A = [1 2 3; 4 5 6]
Output
[
1 2 3
4 5 6
]
Example
This example creates a 3x3 array with numbers from 1 to 9 arranged in rows.
matlab
B = [1 2 3; 4 5 6; 7 8 9] disp(B)
Output
[
1 2 3
4 5 6
7 8 9
]
Common Pitfalls
Common mistakes when creating arrays include:
- Using commas and semicolons incorrectly (commas separate columns, semicolons separate rows).
- Mixing row lengths, which causes errors because MATLAB arrays must be rectangular.
- Forgetting square brackets, which leads to syntax errors.
matlab
Wrong: C = [1, 2; 3 4 5] % Rows have different lengths Right: C = [1 2 0; 3 4 5] % Rows have equal lengths
Quick Reference
| Syntax | Description |
|---|---|
| [1 2 3] | Row vector with elements 1, 2, 3 |
| [1; 2; 3] | Column vector with elements 1, 2, 3 |
| [1 2; 3 4] | 2x2 matrix with two rows and two columns |
| 1:5 | Row vector with elements from 1 to 5 |
| zeros(2,3) | 2x3 matrix of zeros |
| ones(3,1) | 3x1 column vector of ones |
Key Takeaways
Use square brackets [] to create arrays in MATLAB.
Separate elements in a row with spaces or commas, and separate rows with semicolons.
All rows must have the same number of elements to form a valid array.
Use built-in functions like zeros() and ones() for special arrays.
Check syntax carefully to avoid common errors with separators.