You are on page 1of 74

MATLAB Basics & Graphics

Dr. R. Uppaluri Department of Chemical Engineering, Indian Institute of Technology, Guwahati. Email: ramgopalu@iitg.ernet.in

Contents
1. 2. 3. 4. 5. 6. 7. 8. 9. Quick Overview Data Types & Variables Operators Flow Control Functions Input/Output Array Manipulation Writing & Running Programs Plotting

1. Quick Overview
MATLAB is termed as MATRIX LABORATORY High Level Computer Language Scientific Computing Data Visualization Interactive Programming Environment Quick Testing and Debugging Allows one to focus more on principles of programming rather than on programming itself Programs can be developed in a Shorter Time than equivalent FORTRAN or C Programs Negative: No Stand-alone applications i.e., Programs have to be run on MATLAB environment only.

1. Quick Overview Advantages


Large number of functions involving numerical libraries LINPACK, ODE Solver, PDE Solver, Optimization routines etc. Many common tasks accomplished in single function call Solution of Simultaneous Equations Extensive Graphics Support Plotting results with few statements All Numerical Objects treated as Double-Precision Arrays No need to declare data types and carry out type conversion

1. Quick Overview Illustration of Advantages


Gauss Elimination Code in Fortran 90 Use prec_mod conveys to load module prec_m module. DP used for defining floating point numbers Array a(k, k+1:n) a feature not available in previous versions of fortran Code is lengthy

1. Quick Overview Illustration of Advantages


Equivalent MATLAB function (No Subroutines in MATLAB) No Definitions for floating numbers Arrays dynamically defined Built in MATLAB

CODE
Code is shorter and simpler than equivalent FORTRAN code

1. Quick Overview Solution of simultaneous equations

code
Unlike FORTRAN & C Compilers, MATLAB can be operated in the interactive mode through its command window (>>)

1. Quick Overview Command Window


Each command executed upon entry In this mode, MATLAB behaves as an electronic calculator Symbol >> is MATLABs prompt for input Percent Sign (%) marks the beginning of comment. Semicolon (;) Separates the rows of a matrix Supresses printout of intermediate results

1. Quick Overview Functions/Programs execution at Command Window


Create functions/programs with .m extension File name identical to name of the function For example, if Gauss Elimination routine is saved as gauss.m, then the following steps can be used in the command window:

2. Data Types & Variables Data Types


Common data types (All regarded by MATLAB as arrays) double (Numerical objects) Char (Strings) Logical (Logical Statements) Numerical Objects Class Double Scalar is treated as 1 x 1 array Strings Sequence of characters Logical True False

2. Data Types & Variables Function_handle: Important Data class


Consists of the character @ followed by name of function E.g., @sin Function handle uses as input argument in function calls Say we have MATLAB function plot(func, x1, x2) that plots specified function func from x1 and x2. Here func is a function of a variable x. Function call to plot sinx from 0 to pi would be plot(@sin, 0, pi)

2. Data Types & Variables Variables


Case sensitive Xstart and xstart are different variables Length of variable unlimited First N characters are significant For this purpose, use namelengthmax to know what is N

2. Data Types & Variables Variables


Variables are local in purpose. If Variables are shared between local function and calling program, then use global statement. Recommended practice: Capital letters for Global variables such as Global X Y

2. Data Types & Variables Built-in constants & Special Variables

2. Data Types & Variables Few examples for Special constants

2. Data Types & Variables Arrays: Can be created in several ways

Can be entered in three lines as 3 x 3 matrix

Can be entered in single line to separate rows with semi-colon

2. Data Types & Variables Be careful with the semicolon !


MATLAB differentiates between row and column vectors with the semicolon MISPLACED SEMICOLON IMPLIES INPUT ERROR DURING CODING. Examples

2. Data Types & Variables


Single quote Operator () For Matrix transpose

Therefore, one has to be careful with even Single Quote Operator while coding

2. Data Types & Variables Access to matrix elements

Cells

2. Data Types & Variables

A Cell is a sequence of arbitrary objects Cells created by enclosing objects in { }

For displaying contents, use celldisp command

Strings

2. Data Types & Variables

A string is a sequence of characters Treated as Character Array in MATLAB Concatenated (adding) using strcat command and extracted using colon (:) as shown in this example

3. Operators
Arthimetic Operators

3. Operators
Arthimetic Operators: Matrices

3. Operators
Division Operators

Scalars
Right division means a/b Left division means b/a

Matrices
Right division: Solution of X*A = B Left division: Solution of A*X = B

3. Operators Elemental Division

3. Operators Comparison Operators

3. Operators
Comparison Operators: Example

Logical Operators
Used for building compounding expressions

3. Operators
Logical Operators: Example

4. Flow Control
Conditionals

Single condition

Multiple Conditions {Follows with an else statement in the last}

4. Flow Control
Conditionals: Example

4. Flow Control
Conditionals: Switch Statement
Here Expression is evaluated, control is passed to the case that matches the value

Multiple Conditions

4. Flow Control Switch Statement: Example

CODE

4. Flow Control Loops: While Statement

Program for calculating number of years for compoundnig $ 1,000 with 6 % annual interest to $ 10,000

4. Flow Control Loops: for Statement

Program for computing cos x from 0 to pi/2 with 5 intervals

4. Flow Control
Tip: Loops be avoided when Vectors can be used

This is because Vectors execute faster in MATLAB than loops

Recall MATLAB is MATRIX Laboratory!

4. Flow Control
Break statement
Any loop can be terminated by the break statement Upon encountering a break statement, control is passed to the first statement outside the look.

buildvec constructs a row vector of arbitrary length by prompting its elements. When an empty element is encountered, break statement allows ignoring the statement

4. Flow Control Continue Statement


When continue statement is encountered in a loop, control is passed to next iteration without executing the statements in the current iteration.
Strips all blanks from string s1

4. Flow Control Return Statement


Normally, function returns to the calling program when it runs out of the statements Return command forces to exit.
If the error is less than 10-6, then the programme is terminated with in the stipulated number of iterations.

4. Flow Control
Error Statement
Program execution can be terminated with the error function

5. Function Function Definition


Arguments separated by commas Number of arguments may be zero For only one output argument, enclosing brackets can be ommitted. Function should be saved with the file name function_name.m Then only function can be accessible to other program units File may have other functions subfunctions Subfunctions called only by primary function function_name or other subroutines in the file Subfunctions not accessible to other program units

5. Function Calling Functions


Function can be called with fewer arguments than appearing in the function definition Number of input & output arguments used in the function call can be determined by the functions nargin & nargout respectively

Above function has two inputs: x and epsilon Also has two outputs: x and numIter

5. Function Calling Functions


Error tolerance epsilon is an optional input that may be used to override the default value 10-6

code

5. Function Calling Functions


Output argument numIter which contains number of iterations may also be omitted from the function call

5. Function Evaluating Functions


Here we write the dx expression as a function in a different file named myfunc.m and link it to the source code.
In this code, if dx is defined as yourfunc(x), then unless the function is renamed as y = yourfunc(x) and the file name changed as yourfunc.m things will not work

Solve.m myfunc.m

5. Function code Use of function handle

Here, call solve(@myfunc, 2) creates a function handle to myfunc and passes it to solve as an argument Hence, the variable func in solve contains the handle to myfunc Function passed to another function by its handle is evaluated by feval function.

5. Function Inline functions


Not complicated functions can be expressed in inline function

6. Input/Output Reading input

6. Input/Output Printing Output

6. Input/Output Printing Output

7. Array Manipulation Creating Arrays

Colon operator

7. Array Manipulation Linspace command

Logspace command

zeros

7. Array Manipulation

ones

rand

eye

8. Writing and Running Programs


MATLAB has two windows Command Window Interactive mode Any statement that entered gets processed Can be used for learning syntax and trying out basic ideas. Editor/Debugger Type & Save Programs & Functions MATLAB editor has colour coding and automatic indentation

8. Writing and Running Programs


How to Run Programmes File must be saved as M file first A program can be run by invoking the run command from editors debug menu. Variables created during MATLAB session are saved in MATLAB workspace until they are cleared. Variables are cleared using clear statement.

9. Plotting
Example 1: Plot sin x and cos x on a two dimensional plot

9. Plotting
Example 1: Plot sin x and cos x on a two dimensional plot

Example 2: Semilog plot

9. Plotting

Example 2: Semilog plot

9. Plotting

CODE

9. Plotting
Example 3: Polar co-ordinates

y = linspace(0,2*pi,10 0); x = sin(2*x); polar(x,y);

CODE

9. Plotting
Example 4: Pie chart

pie(X) draws a pie chart using the data in X. Each element in X is represented as a slice in the pie chart. pie(X,explode) offsets a slice from the pie. explode is a vector or matrix of zeros and nonzeros that correspond to X. h = pie(...) returns a vector of handles to patch and text graphics objects.

Example 4: Pie chart

9. Plotting

x = [1 3 0.5 2.5 2]; explode = [0 1 0 0 0]; pie(x,explode) colormap jet

CODE

9. Plotting
Example 5: Bar Chart

A bar graph displays the values in a vector or matrix as horizontal or vertical bars bar(Y) draws one bar for each element in Y. If Y is a matrix, bar groups the bars produced by the elements in each row. bar(x,Y) draws a bar for each element in Y at locations specified in x, where x is a monotonically increasing vector defining the x-axis intervals for the vertical bars.

9. Plotting
Example 5: Bar Chart

x = -2.9:0.2:2.9; bar(x,exp(x.*x),'r')

CODE

3-Dimensional graph plotting


3-Dimensional graphs include Normal 3-D graph Meshes Surfaces Contour

3-Dimensional graph plotting


3- D graphs plot3(x,y,t)- used to plot a 3- D graph of a point in space with coordinates of arrays x,y,t. h = plot3(...) returns a column vector of handles to lineseries graphics objects, with one handle per object.

3-Dimensional graph plotting


Example 1: using plot3 command

t = -10*pi:pi/100:10*pi; x = t.*cos(t); y = t.*sin(t); h = plot3(x,y,t); title('Curve u(t) = < t*cos(t), t*sin(t), t >') xlabel('x') ylabel('y') zlabel('z') grid

CODE

3-Dimensional graph plotting


Mesh command
x=[012]; y=[101214]; [xi,yi]=meshgrid(x,y) output >>xi= 012 012 012 >>yi = 101010 121212 141414

It is used to create a mesh meshgrid This function generates two 2-dimensional arrays for 3-D plots.

3-Dimensional graph plotting


Example 2: using mesh command

x = -1:0.05:1; y = x; [xi, yi] = meshgrid(x,y); zi = yi.^2 - xi.^2; mesh(xi, yi, zi) axis off

CODE

3-Dimensional graph plotting


Example 3: using meshc command
To plot the graph of the mesh surface together with the contour plot beneath the plotted surface use function meshc x = -1:0.05:1; y = x; [xi, yi] = meshgrid(x,y); zi = yi.^2 - xi.^2; meshc(xi, yi, zi) axis off

CODE

3-Dimensional graph plotting


surf is used to visualize data as a shaded surface. surfc is used to visualize data as a shaded surface with the contour plot beneath the plotted surface use function meshc

3-Dimensional graph plotting


contour is used to create the contour surface of the graph
[X,Y] = meshgrid(-2:.2:2,2:.2:3); Z = X.*exp(-X.^2-Y.^2); contour(X,Y,Z)

Example 4: drawing contours of a 3D graph

CODE

3-Dimensional graph plotting


Setting the Viewpoint MATLAB enables user to control the orientation of the graphics displayed in an axes. user can specify the viewpoint, view target, orientation, and extent of the view displayed in a figure window. The view command specifies the viewpoint by defining azimuth and elevation with respect to the axis origin.

3-Dimensional graph plotting


MATLAB automatically selects a viewpoint that is determined by whether the plot is 2-D or 3-D. For 2-D plots, the default is azimuth = 0 and elevation = 90. For 3-D plots, the default is azimuth = 37.5 and elevation = 30.

3-Dimensional graph plotting


Example 5: using view command

[X,Y] = meshgrid([2:.25:2]); Z = X.*exp(-X.^2 -Y.^2); surf(X,Y,Z) view([180 0])

CODE

You might also like