Download - Matlab Basic Tutorial
By Muhammad Rizwan
I060388
For Section A&B C&D
INTRODUCTION TO MATLAB
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
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 PerformedA+BA-BA*BC’B=C
A ,B ,C are variables
MATLAB VariablesScalar
A = 4Vector
A = [2 3 4]Matrices
A=
Numbers & Formats
Matlab recognizes several dierent kinds of numbers
Format Set display format for output
FormatSyntax1)format type2)format('type')Both types can be used for same purpose
To see current format write get(0,'format')
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
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 matrixA(2,3) //returns element at 2,3 positionA(2,:) // returns 2nd rowA(:,3) //returns 3rd coloumn
Matrix OperationsA+BA-BA*Bb*A // b is a vector either row or
column vector
Transpose of a matrixC’B=C’
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?
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
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)
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.
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.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
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-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.
Functions Formatfunction [x, y] = myfun(a, b, c) % Function
definition
a , b , c are input parameters and x , y are output parameters
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''.
addtwo.m // without output parametersfunction 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 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.
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
forfor variable = expression statement ... statementEndExamplefor i = 1:m for j = 1:n H(i,j) = 1/(i+j); endend
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.
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.