KEMBAR78
Matlab Basic Tutorial | PPT
By  Muhammad  Rizwan I060388 For Section A&B C&D
INTRODUCTION TO MATLAB
MATLAB It stands for MATrix LABoratory  It is developed by  The Mathworks, Inc .   (http://www.mathworks.com)  It is widely used in mathematical computation Numerical Computation Linear Algebra Matrix Computations Simple Calculations Scripting Graphing
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
 
 
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
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)
 
Operations Performed A+B A-B A*B C’ B=C A ,B ,C are variables
MATLAB Variables Scalar A = 4 Vector A = [2  3  4] Matrices A=
Numbers & Formats Matlab recognizes several dierent kinds of numbers
Format  Set display format for output
Format Syntax format  type format('type') Both types can be used for same purpose To see current format write  get(0,'format')
Some Basics Can act as a calculator x = 3-2^4 Variable names Legal names consist of any combination of letters  and digits, starting with a letter.  These are allowable: NetCost, Left2Pay, x3, X3, z25c5 These are not allowable: Net-Cost, 2pay, %x, @sign
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
Input and Output size(A)  //return size of a matrix Seeing a matrix A(2,3)  //returns element  at 2,3 position A(2,:)  // returns 2 nd  row A(:,3)  //returns 3 rd  coloumn
Matrix Operations A+B A-B A*B b*A  // b is a vector either row or column vector Transpose of a matrix C’ B=C’
Matrix Operations   (Contd) Augmented matrix [B b] [A;C] [C A;A C] Diagonal matrix D=diag([1 2 3])  // create diagonal matrix Diag(D)  // return diagonal diag(diag(D))  what it can do?
Matrix Powers Product of A with itself k If A is square matrix and k is positive integer >>A^k Displaying an Identity Matrix having the same size as A >>A^0 Identity Matrix >>eye(3) >>t=10; eye(t) >>eye(size(A)) display an Identity Matrix the same size as A
Some Basics  (Contd) shortcut for producing row vectors: 1:4 1:3:20 Plotting a graph x = linspace (0,1,10);  // from 0 to 1 divide in 10 parts y = sin(3*pi*x); plot(x,y)
Script M-Files typing at the Matlab becomes tedious, when number 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.
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.
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:
Add.m % comments a=1 b=2 d=a-b; c=a+b
add.m Save as add.m To 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
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
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: ')
M-Files M-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.
Functions  Format function [x, y] = myfun(a, b, c) %  Function definition a , b , c  are  input parameters and x , y are output parameters
Functions function [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''.
addtwo.m   // without output parameters function addtwo(x,y)  % addtwo(x,y) Adds two numbers, vectors, whatever, and  % print the result = x + y  x+y
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
Flow Control If Conditionally execute statements Syntax: if expression statements end expression  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.
Logical comparisons
MATLAB supports these variants of the ``if'' construct  if ... end  if ... else ... end  if ... elseif ... else ... end
if ... end  >> d = b^2 - 4*a*c;  >> if d<0  >>  disp('warning: discriminant is negative, roots are imaginary');  >> end
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
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
for for  variable = expression statement ... statement End Example for i = 1:m for j = 1:n H(i,j) = 1/(i+j); end end
Note no 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.
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.
Example while i = 2; while i<8  i = i + 2  end  Output: i = 4 i = 6  i = 8
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)
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)
Bar Graphs >> x = magic(3)  // creat 3x3 matrix >>x = 8 1 6 3 5 7 4 9 2 >> bar(x)  >> grid
Surface Plots   >> Z = peaks;  // already implemented function >> surf(Z)
Explore it yourself
See Mat lab libraries  in C:\Program Files\MATLAB\R2006b\toolbox See  Help Menu
Thanks  for  your patience
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.
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.

Matlab Basic Tutorial

  • 1.
    By Muhammad Rizwan I060388 For Section A&B C&D
  • 2.
  • 3.
    MATLAB It standsfor MATrix LABoratory It is developed by The Mathworks, Inc . (http://www.mathworks.com) It is widely used in mathematical computation Numerical Computation Linear Algebra Matrix Computations Simple Calculations Scripting Graphing
  • 4.
    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
  • 5.
  • 6.
  • 7.
    Starting MATLAB Tostart 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
  • 8.
    Quitting MATLAB Toend 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)
  • 9.
  • 10.
    Operations Performed A+BA-B A*B C’ B=C A ,B ,C are variables
  • 11.
    MATLAB Variables ScalarA = 4 Vector A = [2 3 4] Matrices A=
  • 12.
    Numbers & FormatsMatlab recognizes several dierent kinds of numbers
  • 13.
    Format Setdisplay format for output
  • 14.
    Format Syntax format type format('type') Both types can be used for same purpose To see current format write get(0,'format')
  • 15.
    Some Basics Canact as a calculator x = 3-2^4 Variable names Legal names consist of any combination of letters and digits, starting with a letter. These are allowable: NetCost, Left2Pay, x3, X3, z25c5 These are not allowable: Net-Cost, 2pay, %x, @sign
  • 16.
    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
  • 17.
    Input and Outputsize(A) //return size of a matrix Seeing a matrix A(2,3) //returns element at 2,3 position A(2,:) // returns 2 nd row A(:,3) //returns 3 rd coloumn
  • 18.
    Matrix Operations A+BA-B A*B b*A // b is a vector either row or column vector Transpose of a matrix C’ B=C’
  • 19.
    Matrix Operations (Contd) Augmented matrix [B b] [A;C] [C A;A C] Diagonal matrix D=diag([1 2 3]) // create diagonal matrix Diag(D) // return diagonal diag(diag(D)) what it can do?
  • 20.
    Matrix Powers Productof A with itself k If A is square matrix and k is positive integer >>A^k Displaying an Identity Matrix having the same size as A >>A^0 Identity Matrix >>eye(3) >>t=10; eye(t) >>eye(size(A)) display an Identity Matrix the same size as A
  • 21.
    Some Basics (Contd) shortcut for producing row vectors: 1:4 1:3:20 Plotting a graph x = linspace (0,1,10); // from 0 to 1 divide in 10 parts y = sin(3*pi*x); plot(x,y)
  • 22.
    Script M-Files typingat the Matlab becomes tedious, when number 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.
  • 23.
    Script M-Files ScriptFile: 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.
  • 24.
    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:
  • 25.
    Add.m % commentsa=1 b=2 d=a-b; c=a+b
  • 26.
    add.m Save asadd.m To 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
  • 27.
    Matlab functions usefulin 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
  • 28.
    Matlab functions usefulin 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: ')
  • 29.
    M-Files M-files canbe 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.
  • 30.
    Functions Formatfunction [x, y] = myfun(a, b, c) % Function definition a , b , c are input parameters and x , y are output parameters
  • 31.
    Functions function [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''.
  • 32.
    addtwo.m // without output parameters function addtwo(x,y) % addtwo(x,y) Adds two numbers, vectors, whatever, and % print the result = x + y x+y
  • 33.
    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
  • 34.
    Flow Control IfConditionally execute statements Syntax: if expression statements end expression 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.
  • 35.
  • 36.
    MATLAB supports thesevariants of the ``if'' construct if ... end if ... else ... end if ... elseif ... else ... end
  • 37.
    if ... end >> d = b^2 - 4*a*c; >> if d<0 >> disp('warning: discriminant is negative, roots are imaginary'); >> end
  • 38.
    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
  • 39.
    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
  • 40.
    for for variable = expression statement ... statement End Example for i = 1:m for j = 1:n H(i,j) = 1/(i+j); end end
  • 41.
    Note no semicolonis 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.
  • 42.
    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.
  • 43.
    Example while i= 2; while i<8 i = i + 2 end Output: i = 4 i = 6 i = 8
  • 44.
    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)
  • 45.
    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)
  • 46.
    Bar Graphs >>x = magic(3) // creat 3x3 matrix >>x = 8 1 6 3 5 7 4 9 2 >> bar(x) >> grid
  • 47.
    Surface Plots >> Z = peaks; // already implemented function >> surf(Z)
  • 48.
  • 49.
    See Mat lablibraries in C:\Program Files\MATLAB\R2006b\toolbox See Help Menu
  • 50.
    Thanks for your patience
  • 51.
    Write a scriptfile 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.
  • 52.
    Write a scriptfile 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.