0% found this document useful (0 votes)
10 views

MATLAB PPT

Matlab tutorial

Uploaded by

rAul'zZ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

MATLAB PPT

Matlab tutorial

Uploaded by

rAul'zZ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Computational Techniques

(MTH563)

Rahul Kumar
Assistant Professor
Department of Mathematics
Lovely Professional University

Lecture Series: MATLAB Programming


MTH563 2/38 Lecture : MATLAB

Table of Contents
1 Course Introduction
Course Details
Course Outcomes
Evaluation & Task Details
Syllabus
Textbooks
2 Computational Techniques
Introduction
Why this course?
How this course?
3 MATLAB
Introduction to MATLAB
MATLAB Environment
4 Basic Syntax and General Purpose Commands
Basic Syntax
General Purpose Commands
Rahul, Asstt. Prof. (LPU)
MTH563 3/38 Lecture : MATLAB

Table of Contents
5 Common Formatting MATLAB Functions

6 Managing a session

7 Working with the System

8 Mathematical calculation in MATLAB.

9 Files in MATLAB

Rahul, Asstt. Prof. (LPU)


MTH563 4/38 Lecture : MATLAB

Course Details

Course Title : Computational Techniques


Course Code : MTH563
Course Weightage : ATT: 5 CAP: 45 ETP: 50
Course Focus : Employability, Skill Development
L-T-P : 0-0-3
Credits : 2

Rahul, Asstt. Prof. (LPU) Course Introduction Course Details


MTH563 5/38 Lecture : MATLAB

Course Outcomes

This course will enable students to:

CO1 : define the working approach of MATLAB software,


CO2 : demonstrate creation of program files in MATLAB while working with array and matrices,
CO3 : illustrate the progamming concept with the use of functions and loops,
CO4 : apply the commands to plot 2D and 3D graphs in MATLAB.

Rahul, Asstt. Prof. (LPU) Course Introduction Course Outcomes


MTH563 6/38 Lecture : MATLAB

Evaluation & Task Details

Evaluation Weightage
Attendance : 5
CA : 45 (best 2 of 3)
MTP : NA
ETP : 50
Total : 100

Details of Academic Task(s)


CA Nature of Task Mode of Task Marks Allottment/ Submission Week
CA1 individual offline 30 4/5
CA2 individual offline 30 8/9
CA3 individual offline 30 11/12

Rahul, Asstt. Prof. (LPU) Course Introduction Evaluation & Task Details
MTH563 7/38 Lecture : MATLAB

Syllabus
1 To learn working in MATLAB with a brief overview.
2 Implementing common formatting MATLAB functions.
3 To perform mathematical calculation in MATLAB.
4 To work with script files and learn the execution of programs.
5 To create vectors and arrays in MATLAB.
6 To create special arrays and perform operations on arrays.
7 To use inbuilt functions for array handling.
8 To solve system of simultaneous linear equations.
9 To create and edit graphs in MATLAB.
10 To plot graph of a mathematical equation in 2D & 3D.
11 To create and execute a function file in MATLAB.
12 Designing program in MATLAB using control statements(if-else).
13 Designing program using loop control statements (for loop).
Rahul, Asstt. Prof. (LPU) Course Introduction Syllabus
MTH563 8/38 Lecture : MATLAB

Syllabus

14 Designing program using loop control statements (while loops).


15 To interpolate the data and fitting of curve numerically using MATLAB.
16 Calculating derivative and integral of a given data numerically using MATLAB.
17 Designing program using loop control statements (break, continue and return statements).
18 To use MATLAB ode45 algorithm in a single variable to solve ODE.
19 To use MATLAB function fsolve in single and multiple variables.

Rahul, Asstt. Prof. (LPU) Course Introduction Syllabus


MTH563 9/38 Lecture : MATLAB

Textbooks

S.No. Title Author Publisher


1. Getting Started with MATLAB Rudra Pratap Oxford University Press
2. Introduction To Matlab Programming, Jaydeep Chakravorty Universities Press Pvt.
Toolbox and Simulink Ltd.

Rahul, Asstt. Prof. (LPU) Course Introduction Textbooks


MTH563 10/38 Lecture : MATLAB

Introduction

Computation: Computation means any type of arithmetic or non-arithmetic calculation


that is well-defined.
Computational Techniques: Computational techniques refer to a set of methods,
algorithms, and approaches based on step-wise, repeated or iterative solution methods and
are used to solve complex engineering/scientific problems involving huge amount of data
by the use of computers which are otherwise be tedious or unsolvable by hand-calculations.
Examples include:
Numerical Methods
Simulation
Data Analysis
Optimization techniques
Artificial Intelligence and Machine Learning, etc.

Rahul, Asstt. Prof. (LPU) Computational Techniques Introduction


MTH563 11/38 Lecture : MATLAB

Why this course?

This course will develop the ability


to identify, formulate, and solve complex engineering problems by applying principles of
engineering, science, and mathematics,
and to efficiently conduct appropriate experimentation, analyze and interpret data, and
use engineering judgment to draw conclusions.

Rahul, Asstt. Prof. (LPU) Computational Techniques Why this course?


MTH563 12/38 Lecture : MATLAB

How this course?

The first step to get started with computational techniques is understanding the basics of
Programming. Computational techniques involve writing codes/programs to perform
calculations and simulations.
Therefore, a programming language like MATLAB which is widely used in scientific computing
and has a rich ecosystem of libraries for various computational tasks is required.

Rahul, Asstt. Prof. (LPU) Computational Techniques How this course?


MTH563 13/38 Lecture : MATLAB

Introduction to MATLAB

MATLAB (MATrix LABoratory) is a high-level multi-paradigm programming language and


interactive environment for numerical computation, visualization and programming. MATLAB
is developed by Math Works.
Developed by Cleve Moler in the late 1970s.
Successor of LINPACK (Linear system package) and EISPACK (Eigen system package)
projects.
Written in C, C++, Java.
Initial release:1984 (39 years ago)
Current stable version: R2023a released on February 22, 2023 (5 months ago).
Website: https://www.mathworks.com/products/matlab.html

Rahul, Asstt. Prof. (LPU) MATLAB Introduction to MATLAB


MTH563 14/38 Lecture : MATLAB

Features of MATLAB

The Most important features of Matlab are:


It is a high level programming language.
It is a multi-paradigm programming language.
Provides an interactive environment for exploration, design and problem solving.
Provides a vast library of built in mathematical functions.
Provides built-in graphic tools for creation of custom plots.
Provides functions for integrating MATLAB based algorithms with external applications
and languages such as C, Java, .NET and Microsoft Excel.

Rahul, Asstt. Prof. (LPU) MATLAB Introduction to MATLAB


MTH563 15/38 Lecture : MATLAB

MATLAB’s Power of Computational Mathematics


Following are some commonly used mathematical calculations where it is mostly used:
Dealing with Matrices and Arrays
2-D and 3-D Plotting and graphics
Linear Algebra
Algebraic Equations
Non-linear Functions
Statistics
Data Analysis
Calculus and Differential Equations
Numerical Calculations
Integration
Transforms
Curve Fitting
Various other special functions
Rahul, Asstt. Prof. (LPU) MATLAB Introduction to MATLAB
MTH563 16/38 Lecture : MATLAB

Applications of MATLAB

MATLAB is widely used as a computational tool in science and engineering encompassing the
fields of physics, chemistry, math and all engineering streams. It is used in a range of
applications including (but not limited to)
Signal Processing and Communications
Image and Video Processing
Control systems
Test and measurement
Computational Finance
Computational biology

Rahul, Asstt. Prof. (LPU) MATLAB Introduction to MATLAB


MTH563 17/38 Lecture : MATLAB

Advantages & Disadvantages


Advanteges
Ease of use
Platform Independence
Predefined Functions
Device Independent Plotting
Graphical User Interface

Disadvanteges
It is an interpreted language and therefore may execute more slowly than compiled
languages.
Cross-compiling of Matlab code to other languages is very difficult and requires deep
Matlab knowledge to deal with errors produced.
Matlab is more expensive. The license is very costly, and users need to buy each and every
module and need to pay for the same.
Rahul, Asstt. Prof. (LPU) MATLAB Introduction to MATLAB
MTH563 18/38 Lecture : MATLAB

MATLAB Environment
MATLAB Environment To begin MATLAB, double-click the MATLAB icon on the computer’s
desktop or select MATLAB from the Start or Program menu. Immediately a special window
called the MATLAB desktop appears as shown below:

Figure 1: The graphical interface to the MATLAB Desktop


Rahul, Asstt. Prof. (LPU) MATLAB MATLAB Environment
MTH563 19/38 Lecture : MATLAB

Components of MATLAB Desktop

When MATLAB opens, a special window called the MATLAB desktop appears. This desktop
contains some sub-windows namely
Command Window: A command window is a place in which a user can enter interactive
commands at the command prompt (») to execute certain files or basic operations, and
they will be executed on the spot.
Workspace: It is the place which contains all the variables that can be used by MATLAB
when a particular command, M-file, or function is executed.
Current Directory: The current directory shows the location where the program is held
or the directory from where the current execution is running.

Rahul, Asstt. Prof. (LPU) MATLAB MATLAB Environment


MTH563 20/38 Lecture : MATLAB

Basic Syntax
Basic Syntax
MATLAB environment behaves like a super-complex calculator. You can enter commands at
the command prompt (»).
Since MATLAB is an interpreted environment, as you give a command, it executes it right away.
For example, type a valid expression in command window and pess enter to see the answer.
» 5 + 5 or 3 ∧ 2 or sin(pi/2) or 7/0 or 732 ∗ 20.3.

Use of Semicolon (;)


Semicolon (;) indicates end of statement.
It is also used to suppress/hide the output of a command. Therefore, if you want to
suppress and hide the output for an expression, add a semicolon after the expression. For
example, x = 3; and press enter to see the result.
It also helps in assigning multiple assignments on the same line. For example,
» a = 2; b = 7; c = a * b;

Rahul, Asstt. Prof. (LPU) Basic Syntax and General Purpose Commands Basic Syntax
MTH563 21/38 Lecture : MATLAB

Rules for variable names


A variable name should start with a letter followed by digits, underscores, or letters.
Avoid naming variable names as provided by pre-defined Matlab’s variable names.
Matlab is case sensitive, i.e., small letters and capital letters are treated differently. For
example, variable names PRICE and Price are different.
The maximum length of a variable name is the value that the ‘namelengthmax’ command
returns.
Special symbols anywhere in a variable name are syntactically invalid in Matlab.

Examples of valid names Examples of invalid names


x6 6x
lastValue end
n_factorial n!

Rahul, Asstt. Prof. (LPU) Basic Syntax and General Purpose Commands Basic Syntax
MTH563 22/38 Lecture : MATLAB

General Purpose Commands


Basic Operators
Operator Description
+ Plus; addition operator.
- Minus; subtraction operator.
* Scalar and matrix multiplication operator.
.* Array multiplication operator.
∧ Scalar and matrix exponentiation operator.
.∧ Array exponentiation operator.
Left-division operator.
/ Right-division operator.
. Array left-division operator.
./ Array right-division operator.
: generates regularly spaced elements and represents an entire row or column.
() encloses function arguments and array indices; overrides precedence.
[] enclosures array elements.
··· line-continuation operator.
Rahul, Asstt. Prof. (LPU) Basic Syntax and General Purpose Commands General Purpose Commands
MTH563 23/38 Lecture : MATLAB

Basic Operators
Operator Description
, separates statements and elements in a row.
; separates columns and suppresses display.
% designates a comment and specifies formatting.
’ Quote sign and transpose operator.
.’ Nonconjugated transpose operator.
= Assignment operator.

Special Variables and Constants


Name Description
ans Most recent answer.
eps Accuracy of floating-point
√ precision.
i,j The imaginary unit −1.
Inf Infinity.
NaN Undefined numerical
Q result (not a number).
pi The number .

Rahul, Asstt. Prof. (LPU) Basic Syntax and General Purpose Commands General Purpose Commands
MTH563 24/38 Lecture : MATLAB

Relational Operators
Operator Description
< Less Than
<= Less Than or Equal
> Greater Than
>= Greater Than or Equal
== Equal To
∼= Not Equal TO

Logical Operators
Name Description
∼ NOT
& AND
| OR

Rahul, Asstt. Prof. (LPU) Basic Syntax and General Purpose Commands General Purpose Commands
MTH563 25/38 Lecture : MATLAB

Common Formatting MATLAB Functions


Format commands
By default, MATLAB displays numbers with four decimal place values. This is known as short
format. However, if you want more precision, there are several formatting commands as given
below:
format short: displays 4 digits after decimal.
format long: displays 16 digits after decimal.
format bank: rounds numbers to two decimal places.
format short e: displays in exponential form with four decimal places plus the exponent.
format long e: displays in exponential form with four decimal places plus the exponent.
format rat: gives the closest rational expression resulting from a calculation.

Try the following commands with above format commands and see the results.
x = 7 + 10/3 + 5∧ 1.2
x = pi
x = sqrt(2)
Rahul, Asstt. Prof. (LPU) Common Formatting MATLAB Functions
MTH563 26/38 Lecture : MATLAB

Commands for Managing a Session

MATLAB provides various commands for managing a session. The following are some
important commands:
Command Description
clc Clears command window.
clear Removes variables from memory.
exist Checks for existence of file or variable.
global Declares variables to be global.
help Searches for a help topic.
lookfor Searches help entries for a keyword.
who Lists current variables.
whos Lists current variables (long display).
quit Stops MATLAB.

Rahul, Asstt. Prof. (LPU) Managing a session


MTH563 27/38 Lecture : MATLAB

Commands for Working with the System


MATLAB provides various useful commands for working with the system, like saving the
current work in the workspace as a file and loading the file later and system-related activities
like, displaying date, listing files in the directory, etc.
Command Description
cd Changes current directory.
mkdir create directory under default directory
date Displays current date.
delete Deletes a file.
diary Switches on/off diary file recording.
dir Lists all files in current directory.
load Loads workspace variables from a file.
path Displays search path.
pwd Displays current directory.
save Saves workspace variables in a file.
type Displays contents of a file.
what Lists all MATLAB files in the current directory.
Rahul, Asstt. Prof. (LPU) Working with the System
MTH563 28/38 Lecture : MATLAB

In-built Mathematical Functions

MATLAB has a number of built-in functions, such as square root, sine, cosine, exponential,
etc, functions. The following table gives a list of some commonly used functions:
Command Description
abs finds absolute value of all elements in the matrix
sign signum function
sin,cos,. . . Trignometric functions
asin,acos. . . Inverse trignometric functions
exp Exponential
sqrt Square root a number
rem(y,x) Remainder after dividing y by x
sign(x) Returns sign (+/-) of a number

Rahul, Asstt. Prof. (LPU) Mathematical calculation in MATLAB.


MTH563 29/38 Lecture : MATLAB

In-built Mathematical Functions

Command Description
log,log10 natural logarithm, logarithm (base 10)
ceil,floor round towards +infinity, -infinity respectively
round round towards nearest integer
real,imag real and imaginary part of a complex matrix
sort sort elements in ascending order
sum,prod summation and product of elements
max,min maximum and minimum of arrays
mean,median average and median of arrays
std,var Standard deviation and variance

Rahul, Asstt. Prof. (LPU) Mathematical calculation in MATLAB.


MTH563 30/38 Lecture : MATLAB

MATLAB File types


MATLAB has five types of files for storing information:
M-files: are standard ASCII text files, with a .m extension to the filename
Mat-files: are binary data-files, with a .mat extension to the filename.
Mex-files: are MATLAB-callable FORTRAN and C programs, with a .mex extension to
the filename.
P-files: are the compiled M-files with a ‘.p’ extension that can be executed in MATLAB
directly.
Fig files: are the binary figure files with a ‘.fig’ extension that can be opened again in
Matlab as figure.
Examples:
firstfile.m- Example for M-File.
firstfile.mat-Example for Mat File.
firstfile.fig-Example for ‘Fig’ file.
firstfile.p-Example for P-file.
firstfile.mex-Example for mex file.
Rahul, Asstt. Prof. (LPU) Files in MATLAB
MTH563 31/38 Lecture : MATLAB

Script Files

Scripts files are files that contain multiple sequential lines of MATLAB commands and function
calls that can be executed together. These are simplest kind of code file because they have no
input or output arguments. The extension of script files is (.m)
A script file can be created in following three ways:
Highlight commands from the Command History, right-click, and select Create Script.
On the Home tab, click the New Script button.
Use the edit function. For example, the command
» edit new _file_name
creates (if the file does not exist) and opens the file new _file_name (if the file exist).
If new _file_name is unspecified, MATLAB opens a new file called Untitled.

Rahul, Asstt. Prof. (LPU) Files in MATLAB


MTH563 32/38 Lecture : MATLAB

Creating and Executing Script Files


Create file
Type the following code in the editor:
NoOfStudents = 6000;
TeachingStaff = 150;
NonTeachingStaff = 20;
Total = NoOfStudents + TeachingStaff + NonTeachingStaff;
disp(Total);
Save this file with an appropriate filename (eg: file_1) and the script file is created.

Run File
After creating and saving the file, you can run it in two ways:
Clicking the Run button on the editor window or
Typing the filename (without extension) in the command prompt.
» prog1
Press enter and see the result.
Rahul, Asstt. Prof. (LPU) Files in MATLAB
MTH563 33/38 Lecture : MATLAB

Some useful functions

Function Description
edit Edit or create file
input Request user input
publish Generate view of MATLAB file in specified format
grabcode Extract MATLAB code from file published to HTML
snapnow Take snapshot of image for inclusion in published document

Rahul, Asstt. Prof. (LPU) Files in MATLAB


MTH563 34/38 Lecture : MATLAB

Add Comments to Code


When you write code, it is a good practice to add comments that describe the code because
Comments allow others to understand your code.
You can refresh your memory when you return to it later.
During code development and testing, you also can use comments to comment out any
code that does not need to run.
Different ways to add comments:
To comment statements in a single line, use (%) sign.
To comment out multiple lines of code, use the block comment operators, % and %. The
% and % operators must appear alone on the lines that immediately precede and follow
the block of help text. Do not include any other text on these lines.
To comment out part of a statement that spans multiple lines, use an ellipsis (...) instead
of a percent sign.
To comment out a selection, select the lines of code, go to the Editor tab, and in the
Code section, click the comment button.
Rahul, Asstt. Prof. (LPU) Files in MATLAB
MTH563 35/38 Lecture : MATLAB

Add Comments to Code

Figure 2: Line Comment


Figure 4: Comment in part of a
statement

Figure 3: Block Comment

Following shortcut keys can also be used to comment and uncomment the code:
Windows: Ctrl+R to comment and Ctrl+T to uncomment.
macOS: Command+/ to comment and Command+Option+/ to uncomment.
Linux: Ctrl+/ to comment and Ctrl+Shift+/ to uncomment.

Rahul, Asstt. Prof. (LPU) Files in MATLAB


MTH563 36/38 Lecture : MATLAB

Create and Run Sections in Code

MATLAB code files often contain many commands and lines of text. You typically focus your
efforts on a single part of your code at a time, working with the code and related text in pieces.
For easier document management and navigation, divide your file into sections. Then, you can
run the code in an individual section and navigate between sections, as needed.
Creating Sections
To create a section,
go to the Editor or Live Editor tab and in the Section section, click the Section Break
button.
You also can enter two percent signs (%%) at the start of the line where you want to
begin the new section.
The new section is highlighted with a blue border, indicating that it is selected. If there is only
one section in your code file, the section is not highlighted, as it is always selected.

Rahul, Asstt. Prof. (LPU) Files in MATLAB


MTH563 37/38 Lecture : MATLAB

Create and Run Sections in Code


In the Editor, a section begins with two percent signs (%%). The text on the same line as %%
is called the section title. Including section titles is optional, however, it improves the
readability of the file and appears as a heading if you publish your code.

Figure 5: Sections in a code


Rahul, Asstt. Prof. (LPU) Files in MATLAB
MTH563 38/38 Lecture : MATLAB

Rahul, Asstt. Prof. (LPU) Files in MATLAB

You might also like