Creating a Matrix in MATLAB
Defining a matrix in MATLAB is straightforward. Start by naming your matrix, then enclose each row in square brackets. Separate rows with semicolons, and elements within each row with spaces or commas. $$ A=[a_{11}\:\: a_{12}\:\: a_{13}; \\ \:\:\:\:\:\:\:\:\:\: a_{21}\:\: a_{22}\:\: a_{23}; \\ \:\:\:\:\:\:\:\:\:\: a_{31}\:\: a_{32}\:\: a_{33}; ] $$
A practical example
Here’s how to define a 2x3 matrix (2 rows, 3 columns):
$$ M = \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix} $$
This matrix consists of two rows:
- The first row includes the elements 1, 2, and 3.
- The second row includes the elements 4, 5, and 6.
Note: You can separate elements in each row with spaces or commas, but spaces generally improve readability.
To define the matrix, write each row separated by a semicolon:
M = [row1; row2]
In this case:
M = [ 1 2 3 ; 4 5 6 ]
The result is a matrix with two rows and three columns.
Example 2
Now, let’s create a 3x3 square matrix with three rows and three columns:
$$ M = \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{pmatrix} $$
This matrix consists of three rows:
- The first row includes the elements 1, 2, and 3.
- The second row includes the elements 4, 5, and 6.
- The third row includes the elements 7, 8, and 9.
To define this matrix, write:
M = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
Separate each element with a space.
You could also use commas instead if you prefer:
M = [ 1, 2, 3 ; 4, 5, 6 ; 7, 8, 9 ]
This will give the same result, though using spaces might make it easier to read.