Download presentation
Presentation is loading. Please wait.
1
Part(2) MATLAB
2
MATLAB Matrix Laboratory
High-performance language for technical computing Computation, visualization, and programming in an easy-to-use environment Typical uses include: Math and computation Modelling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including Graphical User Interface building
3
MATLAB Some facts for a first impression:
Everything in MATLAB is a matrix ! MATLAB is an interpreted language, no compilation needed (but possible) MATLAB does not need any variable declarations, no dimension statements, has no packaging, no storage allocation, no pointers Programs can be run step by step, with full access to all variables, functions etc.
5
Matlab has Some Special Variables
6
The Matlab Environment
7
Matlab Operations
9
The ans variable: >> 91.3-14
The results of calculations do not need to be saved to a variable explicitly, if no variable is specified then the result is automatically saved to the ans(answer) variable. This variable may be subsequently used Ex. : >> ans= 77.3 >> z=ans* 2 z = 154.6
10
Semicolon: Semicolon (; ) terminates the current expression and suppresses output (to the screen) of the result volume = pi * radius^2 * height; The value is calculated and stored in volume but not echoed back to the screen. A semicolon should be used on most lines of code as we are not interested in intermediary results >> a = 6; >> b = 7; >> a*b ans= 42
11
: Comma The comma ( ,) can be used to separate multiple statements on the same line. The value of any variables will be echoed to the screen. x=5.7, y=89.12
12
Managing MATLAB Environment
Who :See the current runtime environment clear: remove all variables from memory clc :clear the command window clf :clear the graphics window save :save the workspace environment Load :restore workspace from a disk file Help :help “command”
13
Some Elementary Math Functions
abs(x) absolute value sqrt(x) square root round(x) rounds to nearest fix(x) truncates toward 0 floor(x) rounds down ceil(x) rounds up sign(x) sign of x rem(x,y) remainder of x/y exp(x) e raised to x power log(x) natural log of x log10(x) log to the base 10 log2(x) log to the base 2
14
Some Trigonometric Functions
sin(x) computes the sine of x, x in radians, cos(x) computes the cosine of x, x in radians tan(x) computes the tangent of x, x in radians asin(y) computes the inverse sine, -1 < x < +1 atan(y) computes the inverse tangent, Notice that MATLAB wants angles to be expressed in radians, not degrees. To convert use the relationship 1 degree = pi/180 radians angle_radians = angle_degrees*(pi/180) angle_degrees = angle_radians*(180/pi)
15
EX.:Write a MATLAB program that evaluates the hypotenuse of a right triangle with sides a = 4 and b = 3, shown in Figure 1 MATLAB Solution: >> % enter the following sequence of instructions: >>a = 4; % length of one side of the right triangle >>b = 3; % length of second side of the right triangle >>C = sqrt(a^2+b^2); % length of hypotenuse is evaluated >> Hypotenuse = C; % displays the result or solution >> Hypotenuse Hypotenuse = 5 a C b Figure 1
16
The if-else-end The basic form of if-else for use in a program file is: if condition statements A else statements B end
17
E.X: solve a quadratic equation of the general form: Ax^2 + Bx + C = 0
>>a=2; b=-10; c=12; >>d= b^2-4*a*c; >>if d<0 disp (’complex roots’); else x1=(-b+sqrt(d))/(2*a); x2=(-b-sqrt(d))/(2*a); End >>disp(x1); disp(x2) 3 2
18
Repeating with for In general the most common form of the for loop
(for use in a program, not on the command line) is for index = j:k statements end or for index = j:m:k
19
Ex.: >>for i=1:5 x(i) = 2*i; End >>x ans =
20
Ex.: A program to sum the numbers within the range [1-10].
>>S=0; >>For =1:10; S=S+I; End >>Disp(S) 55
21
Complex Numbers Matlab implicitly supports complex numbers no requirement for special functions to manipulate . For example: » z1=sqrt(-4)+3 z1 = i » z2=z1*(1-i) z2 = i
22
Vectors E.x :enter a statement like x = [1 3 0 -1 5]
In Matlab 0ne dimensional arrays, called vectors Can create row or column vectors Row vector: E.x :enter a statement like x = [ ] Enter the command disp(x) to see how MATLAB displays a vector x=
23
Vectors You can put commas instead of spaces between vector elements if you like. Try this: a = [5,6,7] A vector can also be generated (initialized) with the colon operator, enter the following statements: x = 1:10 (elements are the integers 1, 2, …, 10);
24
Vectors Enter the following statements: x = 1:2:10 x= Or x = 10:-1:1 (elements are the integers 10, 9, …, 1, since the increment is negative);
25
Functions of vectors : sqrt(x) : returns the squart of each element
sum(x) : returns the sum of vector xof vector x prod(x) : returns the product of vector x length(x) : returns the length of vector x max(x) : returns the max value of vector x min(x) : returns the minimum value of vector x mean(x) : returns the max value of vector x size (x) : return the numbers of rows and columns
26
E.x: >>size (A) 1 4 >> A=[5 9 2 4] >> mean(A) ans= 5
>> C=max(A) 9 >>size (A) row columm
27
Array in Matlab Built- IN Math Functions
sum(A) return the sum of the element in A >> sum(A) ans= 20 sort(A) arranges the element of the vector in ascending >> sort(A) ans=
28
Array in Matlab Built- IN Math Functions
[d,n]=max(A) return d the largest element in A n the position of element >> [d,n]=max(A) d= n = 2 C=min(A) return the smallest element in A >> [d,n]=min(A) return d the smallest element in A n the position of element
29
Matrices Two-dimensional arrays, called a matrix in MATLAB often(matrices). Size = rows by columns [r c] = size(array_name) if array_name is a matrix size will work for n-dimension arrays and output size of each dimension into a row vector Basic matrix creation: >> a = [1 2 3; 4 5 6] a =
30
Matrices Transpose: b = a’ result in a = b= 1 2 3 1 4 7 4 5 6 2 5 8
31
Matrices Zeros, ones, eye command
>> zr=zeros(4,4) >> ne=ones(4,3) Zr= ne=
32
Matrices Zeros, ones, eye command
>> idn=eye(4) idn=
33
Operation on Matrix sum(A) - sum each col of A A’ - transpose of A
diag(A) diagonal elements det(A) compute determinant of A inv(A) compute inverse of A mean(A) treats the columns of A as vectors, returning a row vector of mean values.
34
Vectors And Matrices Array addressing
Vector: vr vr(:) gives all row or column elements vr(1:5) gives the first five row or column elements vr(2) gives the second element Matrix: bar bar(1,3) gives the first row, third column element Bar(:,2) gives all elements in the second column Bar(1,:) gives all elements in the first row Bar(3:4,1:3) gives all elements in the third and fourth rows that are in the first through third columns
35
Matrices :EX.: Create a 3x4 Matrix
- Assign a new value to the(3,1) element >> Mat(3,1)=20
36
>> Mat(2,4) – Mat(1,2) ans= -9 >> B=Mat(:,3) B= 6 10 0 >> C=Mat(2,:) C= 4 7 10 2
37
>> E=Mat(2:3,:)
38
Matrix operations Multiplication
If A is a n×m matrix and B is a m×p matrix, their product C will be a n × p matrix >> A=[1 4 2; 5 7 3; 9 1 6; 4 2 8] >> B=[6 1; 2 5; 7 3] >> C= A*B C= 28 27 65 49 98 32 84 38 Define a 4x3 matrix A Define a 3x2 matrix B Multiply matrix A by matrix B and assign the result to C
39
Matrix exponentiation
The matrix operation a2 means a×a, where a must be a square matrix. operator ˆ is used for matrix exponentiation. Ex. : a = 1 2 3 4 the statement a ˆ 2 results : ans = 7 10
40
Inv function : inverse of a matrix
>> B=Inv(A) B= Creating the matrix A Use Inv function to find the inverse of A and assing it to B Multiplication of A and B gives the identity matrix
41
Determinants >> A=[ 6 5; 3 9] >> det(A) = 6*9-5*3 = 39
6 5 = 39 3 9
42
:Ex. Enter the following statements at the command line: >>a = [2 4 8]; >>b = [3 2 2]; >>a .* b >>a ./ b
43
Array in Matlab Built- IN Math Functions
>> A=[1 4 9; ; ] >> B=sqrt(A) B= Creating a 3x3 Matrix B is a 3x3 array in which each element is the square-root of the corresponding element in A
44
Arithmetic operators that operate element by element on Matrix.
45
plotting in MTALAB : 2D graphing 3D graphing
46
2D Graphing (plot function)
To plot two points the second one is function to the first one we write: >>x=[1:10]; >>y=log(x); >>plot(x,y) The out put will be:
47
2D Graphing Draw a graph of sin (x) where x=[0:0.1 :10]
>> y = sin(x); >> plot(x,y), grid
48
If we want to draw a single point we write
>>y=sin([0:0.1:2*pi]); >>plot(y) the out put will be:
49
2D Graphing Adding new curves to the existing graph or adding some feature : Use the hold command to add lines/points to an existing plot. hold on – retain existing axes, add new curves to current axes. Axes are rescaled when necessary. hold off – release the current figure window for new plots
50
Example: >> x=[0:0.1:2*pi]; >> y=sin(x);
>> plot(x,y) >> hold on >> y=cos(x); >> hold off The out put will be
51
Command for 2D Plotting
52
Example for previous command
This is the title We will mix all command in one example: >>x=[0:0.1:2*pi]; >>y=sin(x); >> plot(x,y) >> hold on >> grid >> title('sin wave') >> xlabel('x') >> ylabel('y') >> hold off The out put will be This is the grid This is ylabel This is xlabel
53
Multiple Plot Another example for multiple plot:
Draw the curve by using points”:” The red one Another example for multiple plot: >> x = 0:pi/100:2*pi; >> y1 = 2*cos(x); >> y2 = cos(x); >> y3 = 0.5*cos(x); >> plot(x,y1,'--',x,y2,'-',x,y3,':') >> xlabel('0 \leq x \leq 2\pi') >> ylabel('Cosine functions') >> title('Typical example of multiple plots') The out put will be:
54
Semilogy : X=0:0.1:10; Semilogy(x,10.^2)
55
Semilogx : X=0:0.1:10; Semilogy(x,10.^x)
56
Loglog : X=1:1000; Loglog(x,exp(x)),Grid on
57
Fplot : If we want to Plot function between specified limits we use “fplot” Example: Let y= X2+5x+6 And we want to draw the curve in the interval[1,15] We write: >> fplot(‘y',[1,15]) The out put will be
58
we write meshc to draw 3D graphing
We will not take a deep idea about it just only a small example: >>[X,Y] = meshgrid(-3:.125:3); >>Z = peaks(X,Y); >>meshc(X,Y,Z); The out put will be we write meshc to draw 3D graphing
59
Linear equations
60
Linear equations
61
Linear equations
62
Numerical integration
b q= ∫ f(x) dx a The value of integral the function to be integrated the integration limits q = quad(function ,a , b)
63
Numerical integration
Use numerical integration to calculate the following integral: 8 ∫ (x e^(-x^0.8) ) dx 0 >> q=quad('x.*exp(-x.^0.8)+0.2',0,8) q =
64
Numerical integration
>> quad('1./(1+x.^2)',1,5) ans = 0.5880 >> quad('(1+x)./(7+x.^3)',2,10) 0.4163
65
E X E R C I S E S Solving the quadratic equation:
X^2 – 100x = 0 X^2 – 5x +4 = 0 >> format bank (2 decimal digits) >> format short (4 decimal digits) >> format long (14 decimal digits)
66
E X E R C I S E S format bank a=1;b=-100;c=0.01; root=sqrt(b^2-4*a*c) root = a=1;b=-5;c=4; root1=sqrt(b^2-4*a*c) root2=sqrt(b^2+4*a*c) root1 = 3.00 root2 = 6.40
67
M-file How to write M-File
Choose File ->new->M-File Write the code in the Editor windows Choose File->Save As then write the name then Save Then you can call the M-File by write it is name in the command windows and put the input variables if the M-file take parameters Finally you can see the result
68
E.x: L=input(' Length L='); q=input('q='); A= q*L/2; x=0:0.5:L;
m=-(A*x-q*x.*x/2); disp([x' m']) plot(x,m) ,grid
69
Function format: The Form is:
function (output variables )=function name(input variables)
70
:Function Example function t=trapEx(a,b) t=(b-a)*(a^(-3)+b^(-3))/2; The out put will be if you put a=1 and b=3 >> trapEx (1,3) ans =
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.