Computer Fundamentals MATLAB
M-Files Array Manipulation Complex Numbers
Today’s Lecture
M-files
Large number of commands for a particular solution can be written in a simple text file We give a .m extension to such files and
call then M-files. Advantage is its re-usability
M-files
To create a new m-file, goto file menu: File->New->Blank M-file. Or simply press Ctrl+N. Write all the commands in this text
editor.
M-files
Array Manipulation
Array Indexing Array Construction Array Orientation Standard Arrays
Array Manipulation
Unlike C++, the first element has an index of 1. For example, a 1-by-11 array would have index
from 1 to 11 (not 0 to 10). Individual elements can be accessed by
subscripts; e.g., x(3) would be the 3rd element of array x. A block of elements can be accessed by colon
notation. x(1:5) accesses first five elements.
Array Manipulation: Indexing
Arrays can be accessed in reverse order. x(3:1) would access third, second and first elements. x(5:-2:1) would access fifth, third and first elements. A set of specific elements can also be accessed. x([2 3 5 6 8 7]) would only access the corresponding
elements in the above mentioned order.
Array Manipulation: Indexing
The index or the array subscript must be a positive integer. Like x(1.3) generates an error.
Array Manipulation: Indexing
A ten column vector can be generated by colon notation. x = (1:10); Step size can also be mentioned. x = (1 : .01 : 1) x = linspace( 1 , pi ,10 )
Array Manipulation: Construction
Arrays can be constructed by concatenating two arrays. If a= [1:3]; b= [ 3:5]; x = [ a b]
Array Manipulation: Construction
Rows can be created with the help of semicolons. x= [ 1;2;3;4;5] will be a column matrix. We can also use the transpose operator (‘) to
make a column array a row vector and vice versa.
Array Manipulation: Orientation
Standard arrays are the matrices in which the elements are either all ones, all zeros, or all random. MATLAB has specific commands to generate them. zeros(2,3) generates a 2-by-3 matrix of all zeros. ones(2) generates a 2-by-2 matrix of all ones. eye(3) generates a 3-by-3 identity matrix. rand(3,6) generates by 3-by-6 matrix of random
elements.
Array Manipulation: Standard Arrays
Complex Numbers
MATLAB can handle real as well as complex numbers with utmost ease. The complex part can be mentioned by either i or j. 2+3i; 3+3j; Special functions also exist for complex number
manipulation.
Complex Numbers
The real & imaginary parts can be separated by real() and imag() functions respectively. real(2+3j) = 2 imag(3+6i) = 6; Magnitude and phase can also be obtained.
Complex Numbers