11.1: Creating Matrices and Arrays
- Page ID
- 85005
By Carey A. Smith
For our purposes, an array is 2-dimensional set of numbers.
A matrix is a 2-dimensional set of numbers that is used for linear algebra computations.
MATLAB keeps track of the numbers of rows and columns of a matrix.
User-defined matrices are typically defined in the following 2 equivalent ways:
Method 1: Create a matrix in directly 2-dimensions
M1 = [1 4 7 10
2 5 8 11
3 6 9 12]
Method 2: Create a matrix on 1 line, with semicolons separating the rows:
M2 = [1 4 7 10; 2 5 8 11; 3 6 9 12]
This creates the same matrices, but is not as visually obvious. This method is often used in books to save space on a page.
It is also possible to define MATLAB matrices (arrays) with 3 or more dimensions, but we will only use 2-dimensional arrays in this text.
Built-in functions to create a matrix
zeros(rows,cols)
Example:
z23 = zeros(2,3)
Result:
0 0 0
0 0 0
ones(rows,cols)
Example:
a32 = ones(3,2)
1 1
1 1
1 1
You can create a matrix of all constant values by multiplying a "ones" matrix by a constant.
6*ones(rows,cols)
a32_6 = 6*ones(3,2)
6 6
6 6
6 6
eye(n) = Identity matrix
Example:
I4 = eye(4)
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
magic(n) = Magic square. The sums of all the rows, columns, and diagonals are the same in a magic square.
Example:
m3 = magic(3)
8 1 6
3 5 7
4 9 2
diag(v) When v is a vector, creates a square matrix with diagonal elements = v.
v = [4, 9, 16]
B = diag(v)
4 0 0
0 9 0
0 0 16
diag(M) When M is a matrix, this extracts the diagonal elements of matrix M.
Example using magic square m3:
diag(m3) = [8
5
2]
pascal4 = pascal(4)
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20
It has binomial coefficients