Download presentation
Presentation is loading. Please wait.
1
Introduction To MATLAB
Lecture 3 ch2-part 2 introduction to Matlab
2
introduction to Matlab
Example >>who // no ended with ; what will be happend ??? display all varibales // nothing with display , because there is no variable >>mynum=3; // declare variable name mynum ans save 3 in it , what is the type????? by default type double >>mynum+5// experssion 3+5=8 why 8 is saved ?? ans varaible ans= 8 your variable are: ans mynum >>clear mynum your variable are ans introduction to Matlab
3
introduction to Matlab
Numerical Data Variables are defined with the assignment operator “=“. MATLAB is dynamically typed, meaning that variables can be assigned without declaring their type, and that their type can change. There is no need to define variables as integers, reals,short, long, etc, as in other languages Integers: a=2 Reals: x=-35.2 introduction to Matlab
4
introduction to Matlab
Types Every variable has a type associated with it MATLAB supports many types, which are called classes. (Essentially, a class is a combination of a type and the operations that can be performed on values of that type whos commend shows variables that have been defined in this Command Window (this shows more information on the variables, similar to what is in the Workspace Window) introduction to Matlab
5
introduction to Matlab
Types numbers number with a decimal place single double integer signed int8 int16 int32 int64 unsigned uint16 uint32 uint64 char logical introduction to Matlab
6
introduction to Matlab
Range of number range: which indicates the smallest and largest numbers that can be stored in the type The range of int8 is from -128 to The range can be found for any type by passing the name of the type as a string (which means in single quotes) to the functions intmin and intmax. For example, >> intmin('int8') ans = -128 >> intmax('int8') ans = 127 introduction to Matlab
7
introduction to Matlab
Quick Question What would happen if you go beyond the range for particular type? for example >>int8(200) ans= 127 >>int8(-130) -128 introduction to Matlab
8
introduction to Matlab
TYPE The type char is used to store either single characters (e.g., ‘x’) or strings, which are sequences of characters (e.g., ‘cat’). Both characters and strings are enclosed in single quotes. The type logical is used to store true 1 /false 0 values. By default, numbers are stored as the type double in MATLAB. There are, however, many functions that convert values from one type to another The names of these functions are the same as the names of the types These names can be used as functions to convert a value to that type. This is called casting the value to a different type, or type casting The function class can also be used to see the type of a variable: introduction to Matlab
9
introduction to Matlab
Example >>val=6+3; // declare val and store 9 in it , what is the type??? double >> class(val)// function return the type of val ans= double >>val=int32(val);//int32 casting , convert val from double to int32 and asve the value int val >>class(val)// function that retrun the type of val int32 introduction to Matlab
10
introduction to Matlab
Format Function example: >>2*sin(1.4) ans= 1.9709 The default in MATLAB is to display numbers that have decimal points with four decimal places. the format command can be used to specify the output format of expressions. There are many options, including making the format short (the default) or long. introduction to Matlab
11
introduction to Matlab
>> format long // dispaly 16 dicmial point >> 2 * sin(1.4) ans = >>2*2.5 ans= >> format short 1.9709 5.0000 introduction to Matlab
12
introduction to Matlab
The format command can also be used to control the spacing between the MATLAB command or expression and the result; it can be either loose (the default) or compact. >> format loose >> 5*33 ans = 165 >> format compact introduction to Matlab
13
introduction to Matlab
long expressions can be continued on the next line by typing three (or more) periods, which is the continuation operator, or the ellipsis >> – 5 ... ans = 16 introduction to Matlab
14
introduction to Matlab
Random Numbers The function rand can be used to generate uniformly distributed random real Numbers Calling it generates one random real number in the open interval(0,1). Examples of calling the rand function: >> rand ans = 0.8147 0.9058 introduction to Matlab
15
Generating Random Integers
As the rand function returns a real number, this can be rounded to produce a random integer. For example: >> round(rand*10) rand // rondom number from * 10 round // randi([imin, imax]) returns a random integer in the inclusive range from imin to imax >> randi([3, 6])// select integer random number form 3 to 6 ans = 4 introduction to Matlab
16
Variables and Basic Commands
Can add, subtract, multiply and divide + addition - negation, subtraction * multiplication / division (divided by e.g. 10/5 is 2) \ division (divided into e.g. 5\10 is 2) ^ exponentiation (e.g. 5^2 is 25) Priority Order: Power, division and multiplication, and lastly addition and substraction. Use () to change the priority. introduction to Matlab
17
Variables and Basic Commands
exp(x), log(x) (base e), log2(x) (base 2), log10(x) (base 10), sqrt(x) Trigonometric functions: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), atan2(x) (entre –pi y pi) Other functions: abs(x) (absolute value), int(x) (integer part ), round(x) (rounds to the closest integer), sign(x) (sign function) floor(x) , ceil(x) , rem(x,y) , mod(x,y), sqrt(x), nthroot(x,y) >>nthroot(27,3) ans= Functions for complex numbers: real(z) (real part), abs(z) (modulus). introduction to Matlab
18
MATLAB Relational operators
MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~= example >> 3 < 5 ans = 1 >> 2 > 9 ans = 0 >> class(ans) // return the type os ans ans = logical introduction to Matlab
19
introduction to Matlab
Example >> 5 < 7 ans = 1 >> ans + 3 ans = 4 >> 'a' < 'c' ans = 1 introduction to Matlab
20
introduction to Matlab
MATLAB Condition || or && and ~ not xor, introduction to Matlab
21
introduction to Matlab
22
introduction to Matlab
Matlab editor Write “;” at the end of a line If you don’t want that the intermediate calculus is written in the window while the program is running Write “%” at the beginning of a line to write a comment in the program Write “…” at the end of a line if you are writing a very long statement and you want to continue in the next line introduction to Matlab
23
CH 2 : Vectors and Matrices
introduction to Matlab
24
introduction to Matlab
Vectors and Matrices Often, MATLAB treats ALL variables as 2D matrices Arrays and Vectors: N x 1 or 1 x N matrix Single value: 1 x 1 matrix Matrix: N x N matrix Handling ALL variables as 2D matrices makes things A LOT faster and easier to work with introduction to Matlab
25
introduction to Matlab
Vectors and Matrices Here are some diagrams showing, from left to right, a scalar, a column vector, a row vector, and a matrix: The scalar is 1 x 1, the column vector is 3 x 1 (three rows by one column), the row vector is 1 x 4 (one row by four columns), and the matrix is 2 x 3 (two rows by three columns). All of the values stored in these matrices are stored in what are called elements introduction to Matlab
26
introduction to Matlab
Vectors Defining vectors: Row vectors; elements separated by spaces or comas >> v =[2 3 4] Column vectors: elements separated by semicolon (;) >> w =[2;3;4;7;9;8] Length of a vector w: length(w) introduction to Matlab
27
The Colon Operator and Linspace Function
the colon operator can be used to iterate through these values. For example, 1:5 results in all of the integers from 1 to 5 inclusive: >> vec = 1:5 vec = Note that, in this case, the brackets [ ] are not necessary to define the vector. With the colon operator, a step value can also be specified by using another colon, in the form (first:step:last). For example, to create a vector with all integers from 1 to 9 in steps of 2: >> nv = 1:2:9 nv = introduction to Matlab
28
introduction to Matlab
QUICK QUESTION! What happens if adding the step value would go beyond the range specified by the last, for example >>nv=1:2:6 1 3 5 How can you use the colon operator to generate the vector Answer shown below? >>n=9:-2:1 introduction to Matlab
29
introduction to Matlab
Vectors Declare a vector / array in MATLAB a = [ ] – row vector Spaces mean to move to the next column a = [1;2;3;4] - column vector Semicolon means to move to the next row a = [ ].’ – (.’ operator means to transpose a vector) - column vector No need to specify how big the vector is first before declaring it , MATLAB automatically figures out how big it is introduction to Matlab
30
introduction to Matlab
Vectors How do I access elements in a vector / array? jenny = a(1); NOTE!: No square brackets when accessing an element! Use round brackets! Elements do not start at index 0, they start at index 1! The matrix indices must be positive integer introduction to Matlab
31
introduction to Matlab
Example >>newvec=[ ]; >>newvec(5) ans = 3 >>b=newvec(4:6) >>b= >> newvec([1 10 5]) ans = introduction to Matlab
32
introduction to Matlab
The value stored in a vector element can be changed by specifying the index or subscrip for example : >>b=[ 7 9 3] b= >>b(2)=11 introduction to Matlab
33
introduction to Matlab
By referring to an index that does not yet exist, a vector can also be extended. For example, the following creates a vector that has three elements. By then assigning a value to the fourth element, the vector is extended to have four elements. >> rv = [ ] rv = >> rv(4) = 2 rv = If there is a gap between the end of the vector and the specified element, 0s are filled in. For example, the following extends the variable rv again: >> rv(6) = 13 rv = introduction to Matlab
34
introduction to Matlab
Think about what would be produced by the following sequence of statements and expressions, and then type them in to verify your answers: pvec = 3:2:10 pvec(2) = 15 pvec(7) = 33 pvec([2:4 7]) introduction to Matlab
35
introduction to Matlab
Matrices Defining matrices: It’s not needed to define their size before hand (a size can be defined and changed afterwards). Matrices are defined by rows; the elements of one row are separated by spaces or comas. Rows are separated by semicolon (;). » M=[3 4 5; ] Empty matrix: M=[ ]; Information about an element: M(1,3), a row M(2,:), a column M(:,3). Changing the value of an element: M(2,3)=1; Deleting a column: M(:,1)=[ ], a row: M(2,:)=[ ]; introduction to Matlab
36
introduction to Matlab
256 There must always be the same number of values in each row. If you attempt to create a matrix in which there are different numbers of values in the rows, the result will be an error message, such as in the following: >> mat = [3 5 7; 1 2] Error using vertcat Dimensions of matrices being concatenated are not consistent. introduction to Matlab
37
introduction to Matlab
Iterators can be used for the values in the rows using the colon operator. For example: >> mat = [2:4; 3:5] mat = The separate rows in a matrix can also be specified by hitting the Enter key after each row instead of typing a semicolon when entering the matrix values, as in: >> newmat = [2 6 88 33 5 2] newmat = 33 5 2 introduction to Matlab
38
introduction to Matlab
Matrices Generating matrices: Generating a matrix full of zeros, zeros(n,m) Generating a matrix full of ones, ones(n,m) Generating a matrix with random elements rand(n,m) introduction to Matlab
39
introduction to Matlab
Example >>a=zeros(2,3) a= >>zeros(2) ans= introduction to Matlab
40
introduction to Matlab
Matrices How do I create a matrix in MATLAB? Ex1: a = [ ; ; ; ]; Ex2: a = [ ; ; ; ]; introduction to Matlab
41
introduction to Matlab
Matrices How do I access elements in a matrix? B = a(3,4); No separate brackets for each dimension Comma is used to separate the dimensions All indices to access arrays are offset by 1! Remember: 1st parameter is the row, 2nd parameter is the column introduction to Matlab
42
introduction to Matlab
Matrices How do I access a range of values in a matrix? Suppose I had a matrix already created called ray, how do I get all of the elements in the 1st row? ray = a(1, 1:4); ray = a(1, :); introduction to Matlab
43
introduction to Matlab
Matrices How do I access a range of values in a matrix? NO for loop! The colon ( : ) operator is used to access a range of values 1 : 4 means a range from 1 through 4 for a dimension : by itself means give me all possible values in a dimension Doing : in the 2nd parameter means give me all of the columns! introduction to Matlab
44
introduction to Matlab
Matrices introduction to Matlab
45
introduction to Matlab
Array, Matrix a vector x = [ ] x = a matrix x = [1 2 3; 5 1 4; ] introduction to Matlab
46
introduction to Matlab
Array, Matrix Transpose y = x’ y = 1 2 5 introduction to Matlab
47
introduction to Matlab
Long Array, Matrix t =1:10 t = k =2:-0.5:-1 k = B = [1:4; 5:8] x = introduction to Matlab
48
Generating Vectors from functions
zeros(M,N) MxN matrix of zeros ones(M,N) MxN matrix of ones rand(M,N) MxN matrix of uniformly distributed random numbers on (0,1) x = zeros(1,3) x = x = ones(1,3) x = rand(1,3) introduction to Matlab
49
introduction to Matlab
Dimensions The length and size functions in MATLAB are used to find dimensions of vectors and matrices The length function returns the number of elements in a vector The size function returns the number of rows and columns in a vector or matrix. MATLAB also has a function numel, which returns the total number of elements in any array introduction to Matlab
50
introduction to Matlab
Think about what would be produced by the following sequence of statements and expressions, and then type them in to verify your answers. mat = [1:3; ; 5:-1:3] mat(3,2) mat(2,:) size(mat) mat(:,4) = [8;11;33] numel(mat) introduction to Matlab
51
introduction to Matlab
Matrix Index Given: A(-2), A(0) Error: ??? Subscript indices must either be real positive integers or logicals. A(4,2) Error: ??? Index exceeds matrix dimensions. introduction to Matlab
52
Concatenation of Matrices
x = [1 2], y = [4 5], z=[ 0 0] A = [ x y] B = [x ; y] 1 2 4 5 C = [x y ;z] Error: ??? Error using ==> vertcat CAT arguments dimensions are not consistent. introduction to Matlab
53
introduction to Matlab
Matrices Operations Given A and B: Addition Subtraction Product Transpose introduction to Matlab
54
Operators (Element by Element)
.* element-by-element multiplication ./ element-by-element division .^ element-by-element power introduction to Matlab
55
The use of “.” – “Element” Operation
b = x .* y b= c = x . / y c= d = x .^2 d= x = A(1,:) x= y = A(3 ,:) y= K= x^2 Erorr: ??? Error using ==> mpower Matrix must be square. B=x*y ??? Error using ==> mtimes Inner matrix dimensions must agree. introduction to Matlab
56
Some Built-in functions
mean(A):mean value of a vector max(A), min (A): maximum and minimum. sum(A): summation. sort(A): sorted vector median(A): median value std(A): standard deviation. det(A) : determinant of a square matrix dot(a,b): dot product of two vectors Cross(a,b): cross product of two vectors Inv(A): Inverse of a matrix A introduction to Matlab
57
introduction to Matlab
Vectors and Matrices Example Time! 1) How do we define M in MATLAB syntax? 2) How do we execute a), b), c) and d)? introduction to Matlab
58
introduction to Matlab
Vectors and Matrices introduction to Matlab
59
introduction to Matlab
Vectors and Matrices introduction to Matlab
60
introduction to Matlab
Vectors and Matrices Some useful matrix and vector / array commands eye(n): Creates an n x n identity matrix introduction to Matlab
61
introduction to Matlab
Questions: How do you declare a vector / array in MATLAB? How do I access elements in a vector / array? How do we creates an n x n identity matrix? How do we creates an n x m matrix full of ones? introduction to Matlab
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.