2. Defining matrices in MATLAB
� 1D row vector – [1 2 3 4] or [1,2,3,4]
� 1D column vector – [1;2;3;4]
� 2D matrix – [1 2 3; 4 5 6; 7 8 9]
� Make a 1D row vector from 1 to 100. Tired ?
Use this – [1:1:100] or [1:100].
Try changing the step size.
� ‘:’ means ‘to’
3. Using Colon (:)
� [1:4] gives a row vector containing [1 2 3 4]
� [1:0.5:4] gives a row vector from 1 to 4 with a
step size of 0.5
� Make a vector from 0 to 2π with a step size of
0.01
4. Matrix operators
� Normal operations
� A + B
� A – B
� A*B
� A^2
� Dot (.) operations: Element wise operations
� Y = A.^2
� Y = A.*B
� Y = A.^B
5. Predefined functions for Matrices
� Mathematical
�sin, cos, tan
�log, exp
�sqrt
� Creation
�ones
�zeros
�eye
�rand
� Information
�size
�length
6. Predefined functions for Matrices
� Matrix operations
� sum
� diag
� transpose or ‘
� inv
� det
� eig
� fliplr
� reshape
� flipud
� rot90
� repmat
7. Matrix concatenation
Suppose A, B, C are matrices
� If we write [A B] or [A,B]
� If we write [A;B]
� Similarly [A B C] and [A;B;C]
� [[A B];C]
8. Exercise
� Create a vector of 20 elements in GP with first
term 1 and common ratio ½. Calculate its sum
� Calculate the sum of first 15 elements of the
series
10. Array indices
� A is an n×m matrix
� To extract the 5th row 6th column element
we’ll write A(5,6)
� The difference between Y=A(5,6) and
A(5,6)=Y
� Y=A(5,6) will extract the 5,6 element from A and
save it to Y
� A(5,6)=Y will change the 5,6 element to Y
11. Array indices
� What if we wish to extract multiple columns or
rows?
� A([1 3 7],[1 2])
� Gives a sub-matrix containing elements which were in
1,3 and 7th row and 1 and 2 columns of matrix A
� A([3 2 7],[3 2 3])
� A(:,[5 6])
� Here : means all
� Gives a sub-matrix containing all rows and 5 and 6
columns of matrix A
12. Linear Indexing
� A is 2D but we can use a single index to
extract any element from A
� A(5)
� Same as A(2,2)
A= 2 3 2
3 1 2
6 9 10
13. Exercise
� Extract a diagonal of a square 5x5 matrix
using linear indexing without using inbuilt
command.
14. Logical indexing
� Index with a matrix of 0 & 1
� Return those elements which corresponds to 1
� B=A>0;
� C=A(B);
15. Exercise
� Create a random matrix of 1x100. Change the
elements to 0 which are smaller than 0.33 and
1 which are greater than 0.33 and smaller than
0.67 and 2 which are greater than 0.67
16. Exercise
� A=[1 2 0 6 4 0 2];
� Get a B vector such that B=[1 ½ 0 1/6 ¼ 0 ½],
i.e. reverse the elements which are not 0