matlab basic tutorial

52
By Muhammad Rizwan I060388 For Section A&B C&D

Upload: muhammad-rizwan

Post on 17-May-2015

9.325 views

Category:

Education


1 download

DESCRIPTION

This is matlab tutorial

TRANSCRIPT

Page 1: Matlab Basic Tutorial

By Muhammad Rizwan

I060388

For Section A&B C&D

Page 2: Matlab Basic Tutorial

INTRODUCTION TO MATLAB

Page 3: Matlab Basic Tutorial

MATLABIt stands for MATrix LABoratory It is developed by The Mathworks, Inc.

(http://www.mathworks.com)

It is widely used in mathematical computationNumerical ComputationLinear AlgebraMatrix ComputationsSimple CalculationsScriptingGraphing

Page 4: Matlab Basic Tutorial

Typical Uses•Math and computation•Algorithm development•Modeling, simulation, and prototyping•Data analysis, exploration, and

visualization•Scientific and engineering graphics•Application development, including

graphical user interface building

Page 5: Matlab Basic Tutorial
Page 6: Matlab Basic Tutorial
Page 7: Matlab Basic Tutorial

Starting MATLAB

To start MATLAB, double-click the MATLAB shortcut

or

Click on “Start” and then on “Run” and write ‘matlab’ and then press OK

It will take some seconds and then matlab starts

Page 8: Matlab Basic Tutorial

Quitting MATLAB

To end your MATLAB session, select Exit MATLAB from the File menu.

or type quit or exit in the Command Window.

There are different type of windows Command Window Editor Window (M-File) Figure Window GUI (Graphical User Interface)

Page 9: Matlab Basic Tutorial
Page 10: Matlab Basic Tutorial

Operations PerformedA+BA-BA*BC’B=C

A ,B ,C are variables

Page 11: Matlab Basic Tutorial

MATLAB VariablesScalar

A = 4Vector

A = [2 3 4]Matrices

A=

Page 12: Matlab Basic Tutorial

Numbers & Formats

Matlab recognizes several dierent kinds of numbers

Page 13: Matlab Basic Tutorial

Format Set display format for output

Page 14: Matlab Basic Tutorial

FormatSyntax1)format type2)format('type')Both types can be used for same purpose

To see current format write get(0,'format')

Page 15: Matlab Basic Tutorial

Some BasicsCan act as a calculatorx = 3-2^4Variable namesLegal names consist of any combination

of letters and digits, starting with a letter.

These are allowable: NetCost, Left2Pay, x3, X3, z25c5These are not allowable: Net-Cost, 2pay, %x, @sign

Page 16: Matlab Basic Tutorial

Input and Output (Contd)

• V=[1 1/2 1/6 1/12]• [1 3 5] row vector• [1 3 5]’• [1;3;5] column vector• [1;3;5]’

• [1 3 5;7 8 4] Matrix

Page 17: Matlab Basic Tutorial

Input and Output

size(A) //return size of a matrix

Seeing a matrixA(2,3) //returns element at 2,3 positionA(2,:) // returns 2nd rowA(:,3) //returns 3rd coloumn

Page 18: Matlab Basic Tutorial

Matrix OperationsA+BA-BA*Bb*A // b is a vector either row or

column vector

Transpose of a matrixC’B=C’

Page 19: Matlab Basic Tutorial

Matrix Operations (Contd)Augmented matrix[B b][A;C][C A;A C]Diagonal matrixD=diag([1 2 3]) // create diagonal

matrixDiag(D) // return diagonal

diag(diag(D)) what it can do?

Page 20: Matlab Basic Tutorial

Matrix PowersProduct of A with itself kIf A is square matrix and k is positive integer

>>A^kDisplaying an Identity Matrix having the same size

as A

>>A^0Identity Matrix>>eye(3)>>t=10; eye(t)>>eye(size(A)) display an Identity Matrix

the same size as A

Page 21: Matlab Basic Tutorial

Some Basics (Contd)shortcut for producing row vectors:1:41:3:20

Plotting a graphx = linspace (0,1,10); // from 0 to 1 divide

in 10 partsy = sin(3*pi*x);plot(x,y)

Page 22: Matlab Basic Tutorial

Script M-Files

typing at the Matlab becomes tedious, whennumber of commands increases, want to change the value of one or more

variables, re evaluate a number of commands, typing at the Matlab becomes tedious.

Page 23: Matlab Basic Tutorial

Script M-Files

Script File: Group of Matlab commands placed in a text file with a text editor.

Matlab can open and execute the commands exactly as if they were entered at the Matlab prompt.

The term “script” indicates that Matlab reads from the “script” found in the file. Also called “M-files,” as the filenames must end with the extension ‘.m’, e.g. example1.m.

Page 24: Matlab Basic Tutorial

Script M-Files

choosing New from the File menu in the Matlab Command window and selecting M-file.

Create the file named add.m in your present working directory using a text editor:

Page 25: Matlab Basic Tutorial

Add.m% comments a=1 b=2 d=a-b; c=a+b

Page 26: Matlab Basic Tutorial

add.mSave as add.mTo execute the script M-file, simply type

the name of the script file add at the Matlab prompt:

• % allows a comment to be added

Open your script file Why result of d is not in the screen ?c Compute and display add

Page 27: Matlab Basic Tutorial

Matlab functions useful in M-files:

Take input from user and show result

disp(ans) Display results without identifying variable names

input(’prompt’) Prompt user with text in quotes, accept input until “Enter” is typed

Page 28: Matlab Basic Tutorial

Matlab functions useful in M-files:

The input command is used for user input of data in a script and it is used in the form of an assignment statement. For example:

a = input(‘Enter quadratic coefficient a: ‘);disp('Value of first quadratic root: ')

Page 29: Matlab Basic Tutorial

M-FilesM-files can be either

scripts or functions.

Scripts are simply files containing a sequence of MATLAB statements.

Functions make use of their own local variables and accept input arguments.

Page 30: Matlab Basic Tutorial

Functions Formatfunction [x, y] = myfun(a, b, c) % Function

definition

a , b , c are input parameters and x , y are output parameters

Page 31: Matlab Basic Tutorial

Functionsfunction [output_parameter_list] = function_name(input_parameter_list)

The first word must always be ``function''.Following that, the (optional) output parameters are

enclosed in square brackets [ ]. If the function has no output_parameter_list the square

brackets and the equal sign are also omitted.The function_name is a character string that will be used

to call the function. The function_name must also be the same as the file

name (without the ``.m'') in which the function is stored. In other words the MATLAB function, ``foo'', must be

stored in the file, ``foo.m''.

Page 32: Matlab Basic Tutorial

addtwo.m // without output parametersfunction addtwo(x,y) % addtwo(x,y) Adds two numbers, vectors,

whatever, and % print the result = x + y x+y

Page 33: Matlab Basic Tutorial

Elementary Math Functions >> abs(x) % absolute value of x >> exp(x) % e to the x-th power >> fix(x) % rounds x to integer towards 0 >> log10(x) % common logarithm of x to the

base 10 >> rem(x,y) % remainder of x/y >> sqrt(x) % square root of x >> sin(x) % sine of x; x in radians >> acoth(x) % inversion hyperbolic cotangent of

x >> help elfun % get a list of all available

elementary functions

Page 34: Matlab Basic Tutorial

Flow ControlIfConditionally execute statementsSyntax: if expression statements endexpression is a MATLAB expression, usually

consisting of variables or smaller expressions joined by relational operators (e.g., count < limit), or logical functions (e.g., isreal(A)).

statements is one or more MATLAB statements to be executed only if the expression is true or nonzero.

Page 35: Matlab Basic Tutorial

Logical comparisons

Page 36: Matlab Basic Tutorial

MATLAB supports these variants of the ``if'' construct

if ... end if ... else ... end if ... elseif ... else ... end

Page 37: Matlab Basic Tutorial

if ... end

>> d = b^2 - 4*a*c; >> if d<0 >> disp('warning: discriminant is negative, roots are imaginary'); >> end

Page 38: Matlab Basic Tutorial

if ... else ... end>> d = b^2 - 4*a*c; >> if d<0 >> disp('warning: discriminant is negative, roots are imaginary');>> else >> disp('OK: roots are real, but may be repeated'); >> end

Page 39: Matlab Basic Tutorial

if ... elseif ... else ... end>> d = b^2 - 4*a*c;>> if d<0 >> disp('warning: discriminant is negative, roots are imaginary'); >> elseif d==0 >> disp('discriminant is zero, roots are repeated'); >> else >> disp('OK: roots are real and distinct'); >> end

Page 40: Matlab Basic Tutorial

forfor variable = expression statement ... statementEndExamplefor i = 1:m for j = 1:n H(i,j) = 1/(i+j); endend

Page 41: Matlab Basic Tutorial

Noteno semicolon is needed to suppress output at

the end of lines containing if, else, elseif or endif

elseif has no space between ``else'' and ``if'' the end statement is required the ``is equal to'' operator has two equals

signs Indentation of ``if'' blocks is not required,

but considered good style.

Page 42: Matlab Basic Tutorial

while constructs Repeat statements an indefinite number of times

Syntax: while expression do something end where ``expression'' is a logical expression. The

``do something'' block of code is repeated until the expression in the while statement becomes false.

Page 43: Matlab Basic Tutorial

Example while i = 2; while i<8 i = i + 2 end Output: i = 4 i = 6 i = 8

Page 44: Matlab Basic Tutorial

Graphics MATLAB is an interactive environment in

which you can program as well as visualize your computations.

It includes a set of high-level graphical functions for: Line plots (plot, plot3, polar)

Bar graphs (bar, barh, bar3, bar3h, hist, rose, pie, pie3) Surface plots (surf, surfc)

Mesh plots (mesh, meshc, meshgrid) Contour plots(contour, contourc, contourf) Animation (moviein, movie)

Page 45: Matlab Basic Tutorial

Line Plots

Note:You can also set properties means line size, color, text show ,grid , axis etc.

For this I will place some reference code observe it

>> t = 0:pi/100:2*pi; >> y = sin(t); >> plot(t,y)

Page 46: Matlab Basic Tutorial

Bar Graphs

>> x = magic(3) // creat 3x3 matrix

>>x = 8 1 6 3 5 7 4 9 2 >> bar(x) >> grid

Page 47: Matlab Basic Tutorial

Surface Plots >> Z = peaks; //

already implemented function

>> surf(Z)

Page 48: Matlab Basic Tutorial

Explore it yourself

Page 49: Matlab Basic Tutorial

See Mat lab libraries in C:\Program Files\MATLAB\R2006b\toolbox

See Help Menu

Page 50: Matlab Basic Tutorial

Thanks for your patience

Page 51: Matlab Basic Tutorial

Write a script file which have any mathematical function and write an other script file in which you use this function and apply Newton-Raphson method on it , also draw it.

Page 52: Matlab Basic Tutorial

Write a script file which have any mathematical function and write an other script file in which you use this function and apply Regula-falsi method on it , also draw it.