Part(2) MATLAB.

Slides:



Advertisements
Similar presentations
1 EMT 101 – Engineering Programming Dr. Farzad Ismail School of Aerospace Engineering Universiti Sains Malaysia Nibong Tebal Pulau Pinang Week 10.
Advertisements

Introduction to MATLAB ENGR 1187 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
Builtin and user defined functions
259 Lecture 15 Introduction to MATLAB. 2 What is MATLAB?  MATLAB, which stands for “MATrix LABoratory” is a high- performance language for technical.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
1 Statistical Computing in MATLAB AMS 597 Ling Leng.
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill.
Predefined MATLAB Functions ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
Introduction to MATLAB adapted from Dr. Rolf Lakaemper.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
MATLAB Tutorials Session I Introduction to MATLAB Rajeev Madazhy Dept of Mechanical Engineering LSU.
Copyright © 2006 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 1 MATLAB Programming Chapter 2.
CSE123 Lecture 5 Arrays and Array Operations. Definitions Scalars: Variables that represent single numbers. Note that complex numbers are also scalars,
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
ENG 1181 College of Engineering Engineering Education Innovation Center MATLAB is a powerful program for numerical computations, plotting and programming.
Introduction to MATLAB ENGR 1181 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
Introduction to Engineering MATLAB – 1 Introduction to MATLAB Agenda Introduction Arithmetic Operations MATLAB Windows Command Window Defining Variables.
MATLAB An Introduction to MATLAB (Matrix Laboratory) 1.
EECE 360/460 Matlab Tutorial Jan Outline What is Matlab? What is Matlab? Matlab Interface Matlab Interface Basic Syntax Basic Syntax Plotting Graphs.
Eng Ship Structures 1 Introduction to Matlab.
INTRODUCTION TO MATLAB LAB# 01
Matlab Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
Introduction to MATLAB adapted from Dr. Rolf Lakaemper.
OUTLINE Overview Numbers, variables and similar in Matlab
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
1 EMT 101 – Engineering Programming Dr. Farzad Ismail School of Aerospace Engineering Universiti Sains Malaysia Nibong Tebal Pulau Pinang Week 10.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
Lecture 24: Rough and Ready Analysis. MATLAB uses function names consistent with most major programming languages For example sqrt sin cos log.
Matlab for Engineers Matlab Environment Chapter 2.
MATLAB Lecture 1 염익준. Introduction MATLAB (MATrix LABoratory) a special purpose computer program optimized to perform engineering and scientific calculations.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
CIS 595 MATLAB First Impressions. MATLAB This introduction will give Some basic ideas Main advantages and drawbacks compared to other languages.
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
NoViC, Dept. of Mechanical Eng Acoustics Lab., NoViC 1. Download Matlab 2.
Outline What is MATLAB MATLAB desktop Variables, Vectors and Matrices Matrix operations Array operations Built-in functions: Scalar, Vector, Matrix Data.
Some “What’s the output” questions to get the day started… >>A = [1 2 3; 3 5 6] This statement stores the matrix: 1. A= 2. A= 3. A= 4. A= Ask Garvin’s.
Variables, Operators, and Expressions
Trigonometric Identities
ECE 1304 Introduction to Electrical and Computer Engineering
Introduction to MATLAB
Arithmetic Operations
Introduction to MATLAB
Numeric, Cell and Structural Arrays One of the strenghts of MATLAB is the capabilty to handle collection of numbers called ARRAYS. MATLAB refers to scalars,
ECE 1304 Introduction to Electrical and Computer Engineering
Built-in MATLAB Functions Chapter 3
Introduction to Mat lab
BIL 104E Introduction to Scientific and Engineering Computing
Statistical Computing in MATLAB
Computer Simulation Lab
Matrices and Arrays.
Introduction to MATLAB
INTRODUCTION TO BASIC MATLAB
MATLAB DENC 2533 ECADD LAB 9.
Introduction To MATLAB
Introduction to MATLAB
MATH 493 Introduction to MATLAB
Use of Mathematics using Technology (Maltlab)
Lecture 2 Introduction to MATLAB
Fourth Year – Software Engineering
Communication and Coding Theory Lab(CS491)
Introduction to MATLAB
Introduction to Matlab
INTRODUCTION TO MATLAB
Demo of Basic Matlab Features
Announcements P3 due today
Simulation And Modeling
How to Use MATLAB A Brief Introduction.
Computer Simulation Lab
Presentation transcript:

Part(2) MATLAB

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

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.

Matlab has Some Special Variables

The Matlab Environment

Matlab Operations

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. : >> 91.3-14 ans= 77.3 >> z=ans* 2 z = 154.6

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

: 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

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”

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

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)

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

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

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

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

Ex.: >>for i=1:5 x(i) = 2*i; End >>x ans = 2 4 6 8 10

Ex.: A program to sum the numbers within the range [1-10]. >>S=0; >>For =1:10; S=S+I; End >>Disp(S) 55

Complex Numbers Matlab implicitly supports complex numbers no requirement for special functions to manipulate . For example: » z1=sqrt(-4)+3 z1 = 3.0000+ 2.0000i » z2=z1*(1-i) z2 = 5.0000-1.0000i

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 = [1 3 0 -1 5] Enter the command disp(x) to see how MATLAB displays a vector x= 1 3 0 -1 5

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);

Vectors Enter the following statements: x = 1:2:10 x= 1 3 5 7 9 Or x = 10:-1:1 (elements are the integers 10, 9, …, 1, since the increment is negative);

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

E.x: >>size (A) 1 4 >> A=[5 9 2 4] >> mean(A) ans= 5 >> C=max(A) 9 >>size (A) 1 4 row columm

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= 2 4 5 9

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= 9 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

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 = 1 2 3 4 5 6

Matrices Transpose: b = a’ result in a = b= 1 2 3 1 4 7 4 5 6 2 5 8 1 2 3 1 4 7 4 5 6 2 5 8 7 8 9 3 6 9

Matrices Zeros, ones, eye command >> zr=zeros(4,4) >> ne=ones(4,3) Zr= ne= 0 0 0 0 1 1 1 0 0 0 0 1 1 1

Matrices Zeros, ones, eye command >> idn=eye(4) idn= 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1

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.

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

Matrices :EX.: Create a 3x4 Matrix 3 11 6 5 4 7 10 2 13 9 0 8 - Assign a new value to the(3,1) element >> Mat(3,1)=20 20 9 0 8

>> Mat(2,4) – Mat(1,2) ans= -9 >> B=Mat(:,3) B= 6 10 0 >> C=Mat(2,:) C= 4 7 10 2

>> E=Mat(2:3,:) 4 7 10 2 20 9 0 8

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

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 15 22

Inv function : inverse of a matrix >> B=Inv(A) B= 5.5 -3.5 2.0 2.0 -1.0 0.0 -3.0 2.0 -1.0 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

Determinants >> A=[ 6 5; 3 9] >> det(A) = 6*9-5*3 = 39 6 5 = 39 3 9

:Ex. Enter the following statements at the command line: >>a = [2 4 8]; >>b = [3 2 2]; >>a .* b 6 8 16 >>a ./ b 0.667 2.00 4.00

Array in Matlab Built- IN Math Functions >> A=[1 4 9; 16 25 36; 49 64 81] >> B=sqrt(A) B= 1 2 3 4 5 6 7 8 9 Creating a 3x3 Matrix B is a 3x3 array in which each element is the square-root of the corresponding element in A

Arithmetic operators that operate element by element on Matrix.

plotting in MTALAB : 2D graphing 3D graphing

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:

2D Graphing Draw a graph of sin (x) where x=[0:0.1 :10] >> y = sin(x); >> plot(x,y), grid

If we want to draw a single point we write >>y=sin([0:0.1:2*pi]); >>plot(y) the out put will be:

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

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

Command for 2D Plotting

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

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:

Semilogy : X=0:0.1:10; Semilogy(x,10.^2)

Semilogx : X=0:0.1:10; Semilogy(x,10.^x)

Loglog : X=1:1000; Loglog(x,exp(x)),Grid on

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

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

Linear equations

Linear equations

Linear equations

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)

Numerical integration Use numerical integration to calculate the following integral: 8 ∫ (x e^(-x^0.8) + 0.2 ) dx 0 >> q=quad('x.*exp(-x.^0.8)+0.2',0,8) q = 3.1604

Numerical integration >> quad('1./(1+x.^2)',1,5) ans = 0.5880 >> quad('(1+x)./(7+x.^3)',2,10) 0.4163

E X E R C I S E S Solving the quadratic equation: X^2 – 100x +0.01 = 0 X^2 – 5x +4 = 0 >> format bank (2 decimal digits) >> format short (4 decimal digits) >> format long (14 decimal digits)

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 = 100.00 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

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

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

Function format: The Form is: function (output variables )=function name(input variables)

: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 = 1.0370