Section 2.2 Introduction to Matrices
Subsection 2.2.1 Creating Matrices
A matrix is simply a two-dimensional array. Again, there are several ways in MATLAB to create a matrix. One way is to simply list all of the matrix elements row by row, separating individual rows by semicolons (or carriage returns) and separating elements of a particular row by commas or spaces:
>> variable_name = [row1 elements; row2 elements; ...row_m elements]
Each row must have the same number of elements (
n
). A matrix with m rows and n columns is also called a \(m\times n\) matrix. Here is an example:>> a = [5 20 45; 1 2 4; 3 6 9; 11 4 33]
a =
5 20 45 16
1 2 4 3
6 9 11 4
You can use carriage returns to separate rows:
>> a = [5 20 45 16
1 2 4 3
6 9 11 4]
a = 5 20 45 16 1 2 4 3 6 9 11 4
You can use vectors to make up rows:
>> a = [1:2:11; 0:5:25; linspace(10,60,6)]
a =
1 3 5 7 9 11
0 5 10 15 20 25
10 20 30 40 50 60
Subsection 2.2.2 Fancy Ways of Creating Arrays
Matrices of all zeros, ones, and the identity matrix can be created using functions:
zeros(m,n)
creates a matrix of all zeros, withm
rows andn
columnsones(m,n)
creates a matrix of all ones, withm
rows andn
columnseye(n)
creates an
xx
identity matrix
Here are some examples - type these into your MATLAB prompt and play with the inputs:
>> z = zeros(3,4)
z =
0 0 0 0
0 0 0 0
0 0 0 0
>> won = ones(2,8)
won =
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
>> iyah = eye(4)
iyah =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1