Transcript Lab 2

LAB 2
Vectors and Matrices
Dr.Abdel Fattah FARES
Vectors :
A vector is a one-dimensional array of numbers. MATLAB allows you to create
column vectors or row vectors.
Column vectors
>> a = [2; 1; 4]
a=
2
1
4
row vectors
>> v = [2 0 4]
v=
204
>> w = [1,1,9]
w=
119
>> A = [1
A=
1
2
5
7
13 17
2 3; 5 7 11; 13 17 19]
3
11
19
Transpose operation
In MATLAB, we represent the transpose operation with a single quote or tick
mark (‘). Taking the transpose of a column vector produces a row vector:
Transpose Operator (1)
>> v = [2 4 1 7]
v=
2
4
1
7
>> w = v’
w=
2
4
1
7
Transpose Operator (2)
Add or Subtract two vectors
Vectors with Uniformly Spaced Elements
x = [xi : q : xe]
The length :
The length command returns the number of elements that a vector contains. For
example:
MAX & MIN
>> x=[0:3:10]
x=
0
3
6
9
array multiplication
summation
square root
Matrices :
Matrices scalar multiplication
add and subtract
The transpose
Array multiplication
Matrix Multiplication
Consider two matrices A and B. If A is an m × p matrix and B is a p × n matrix, they can be
multiplied together to produce an m × n matrix. To do this in MATLAB, we leave out the period (.)
and simply write A*B. Keep in mind that if the dimensions of the two matrices are not correct, the
operation will generate an error.
More Basic Operations
Creating vectors with linspace (1)
The linspace function creates vectors with elements having uniform
linear spacing.
Syntax:
x = linspace(startValue,endValue,nelements)
Examples:
>> u = linspace(0.0,0.25,5)
u=
0
0.0625 0.1250 0.1875 0.2500
Creating vectors with linspace (2)
Column vectors are created by appending the transpose operator to
linspace
>> v = linspace(0,9,4)’
v=
0
3
6
9
Special Matrix Types
The identity matrix is a square matrix that has ones along the diagonal and zeros elsewhere.
To create an n × n identity matrix, type the following MATLAB command:
eye(n)
Syntax:
A = eye(n)
A = eye(nrows,ncols)
Let’s create a 4 × 4 identity matrix:
Use ones and zeros to set intial values of a matrix or vector.
Syntax:
A = ones(nrows,ncols)
A = zeros(nrows,ncols)
The diag function can either create a matrix with specified diagonal
elements, or extract the diagonal elements from a matrix
Referencing Matrix Elements
change the value of matrix elements
delete a row or column in a matrix