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 = row vectors >> v = [2 0 4] v = >> w = [1,1,9] w = 1 1 9
>> A = [1 2 3; ; ] A =
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:
>> v = [ ] v = >> w = v’ w = Transpose Operator (1)
Transpose Operator (2)
Add or Subtract two vectors Vectors with Uniformly Spaced Elementsx = [xi : q : xe]
The length command returns the number of elements that a vector contains. For example: The length : MAX & MIN
>> x=[0:3:10] x =
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 =
Creating vectors with linspace (2) Column vectors are created by appending the transpose operator to linspace >> v = linspace(0,9,4)’ v =
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