SlideShare a Scribd company logo
MATLAB – Selection and Repetition Structure
Mechanical Engineering Department
Sardar Vallabhbhai National Institute of Technology, Surat,
Gujarat, India.
mkr@med.svnit.ac.in
Dr. Manish K Rathod
1
 It is developed by The Mathworks, Inc.
(http://www.mathworks.com)
• It is an integrated technical computing environment that
combines numeric computation, advanced graphics and
visualization, and a high-level programming language.
– Interpreted language
– Scientific programming environment
– Very good tool for the manipulation of matrices
– Great visualisation capabilities
– Loads of built-in functions
– Easy to learn and simple to use
– slow (compared with FORTRAN or C) because it is interpreted.
– automatic memory management; no need to declare arrays.
What is MATrix LABoratory ?
Dr. Manish K Rathod, Assistant Professor, MED, SVNIT,
Surat
2
Dr. Manish K Rathod, Assistant Professor, MED, SVNIT,
Surat
3
vast collection of computational algorithms ranging from
elementary functions to more sophisticated functions
high-level matrix/array language with Control flow
statements, functions, data structures, input/output, and
object-oriented programming features.
Mathematical Function Library
MATLAB Language
Dr. Manish K Rathod, Assistant Professor, MED, SVNIT,
Surat
4
5
Computer program
• One way to think of a computer program (not
just MATLAB®) is to consider how the
statements that compose it are organized.
• Usually, sections of computer code can be
categorized as sequences , selection
structures , and repetition structures.
Dr. Manish K Rathod, Assistant Professor, MED, Surat
Computer program
Sequence
• List of commands
that are executed
one after another.
Selection Structure
• Allows the
programmer to
execute one / more
commands if some
criterion is true and
a second command
if the criterion is
false.
Repetition Structure
• A group of
statements to be
executed multiple
times.
• Depends on either a
counter or the
evaluation of a
logical condition.
Dr. Manish K Rathod, Assistant Professor, MED, Surat 6
• Plan your program
– Two common approach
• Graphical approach (Flowchart)
• Verbal description (Pseudocode)
• For simple program, Psdeudocode is best.
– Outline a set of statements describing the steps to
solve a problem
– Convert these steps into an M-file using
appropriate code
Flowchart and pseudo code
Dr. Manish K Rathod, Assistant Professor, MED, Surat 7
1. Wake-up at 7:00 a.m., except Sunday
2. Get ready and reach office before 8:45 a.m.
3. If it is late; take auto, else go by bus
4. Work from 9.00 a.m. to 12.00 a.m.
5. Go to lunch for all days except fast
6. Between 4:00 p.m. to 6:00 p.m. conduct Weekly Meeting
Marketing meeting on Mon, Wed, Fri and
Production meeting on Tue, Thu, Sat
7. On every 1st , check for salary & release important dues
8. Go back to residence
Schedule of an executive
Dr. Manish K Rathod, Assistant Professor, MED, Surat 8
Read Time, Day and Date from watch & calendar
For Day == Mon, Tue, Wed, Thu, Fri and Sat
if (Time > or = 7:00), wake-up (brake)
else go to sleep and check again after some time
% Get ready and reach office before 8:45
while not reached in office hurry up!!!
if it is late; pickup an auto, (i.e. Time > or = 8:00)
else wait for bus until bus arrives
while Time < or = 12:00 work in office (from 9.00 to 12.00)
while (Time == 12:00) & (NOT fast) go to lunch end
while Time ~= 4:00 work in office (from 12.00 to 4.00 PM)
if (Day == Mon) or (Day == Wed) or (Day == Fri)
Conduct Marketing Meeting, end at 6:00
if (Day == Tue) or (Day == Thu) or (Day == Sat)
Conduct Production Meeting, end at 6:00
if Date == 1st Get salary and release important dues
Go back to residence and end the day
Schedule of an executive (pseudo-code)
Dr. Manish K Rathod, Assistant Professor, MED, Surat 9
MATLAB Functions - Basic Features
Mechanical Engineering Department
Sardar Vallabhbhai National Institute of Technology, Surat,
Gujarat, India.
mkr@med.svnit.ac.in
Dr. Manish K Rathod
10
• Programming often requires repeating a set of tasks over
and over again.
• For example, the sin function in MATLAB is a set of
tasks (i.e., mathematical operations) that computes an
approximation for sin(x).
• Rather than having to retype or copy these instructions
every time you want to use the sin function, it is useful
to store this sequence of instruction as a function that
you can call over and over again.
11
Motivations
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• A function is a group of statements that together
perform a task. In MATLAB, functions are defined in
separate files.
• MATLAB functions are similar to C functions or
Fortran subroutines.
• Two types: Inbuilt Functions and, User Defined
Function
12
Motivations
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• You decide to paint your house by some one (which you also can do)
– Main code can perform the required task but for the simplicity outside
party is preferred
• Identifying someone who can do this
– Give a name and write a separate file
• Giving possession of the house to him/them
– Command of the program will be shifted to the function
• Providing them with required material (color containers, brush, etc)
– Submit your variable to function from your control to there control
this may required that variable will be identified by different name
• Observe successful completion of task
– Halt the main program execution till your function will executed
• Get cleaned the floor and other parts of house & take possession
– Delete all the variable & workspace generated by function & get
control back
• Pay the persons and send off them
– Spend required CPU time and terminate the function call 13
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• MATLAB® has an extensive library of built-in functions to
allow to perform mathematical functions, including
logarithms, trigonometric functions, and statistical analysis
functions.
• Many of the names for MATLAB® ’s built-in functions are the
same as those defined not only in the C programming
language, but in Fortran and Java as well. For example,
• To take the square root of the variable x ,
b = sqrt(x)
• A big advantage of MATLAB ® is that function arguments can
generally be either scalars or matrices.
14
Built-in function
Dr. Manish K Rathod, Assistant Professor, MED, Surat
All functions can be thought of as having three components:
a name, input, and output.
• In the preceding example, the name of the function is sqrt , the
required input (also called the argument) goes inside the
parentheses and can be a scalar or a matrix, and the output is a
calculated value or values.
Some functions require multiple inputs.
• For example, the remainder function,
rem , requires two inputs: a dividend and a divisor, i.e. rem(x,y)
rem(10,3) %calculates the remainder of 10 divided by 3:
ans = 1
15
Built-in function
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• The size function is an example of a function that returns
two outputs, which are stored in a single array. It determines
the number of rows and columns in a matrix. Thus,
d = [1, 2, 3; 4, 5, 6];
f = size(d) %returns the 1 X 2 result matrix
f = 2 3
• You can also assign variable names to each of the answers by
representing the left-hand side of the assignment statement
as a matrix. For example,
[rows,cols] = size(d)
rows =
2
cols =
3 16
Built-in function
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• You can create more complicated expressions by nesting
functions. For instance,
g = sqrt(sin(x))
• Finds the square root of the sine of whatever values are
stored in the matrix named x .
• If x is assigned a value of 2,
x = 2;
• the result is
g =
0.9536
17
Built-in function
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• MATLAB ® includes extensive help tools, which are especially
useful in understanding how to use functions.
• There are two ways to get help from within MATLAB® :
– A command-line help function ( help ) and
– an HTML-based set of documentation available by
selecting Help from the menu bar
• For example, to get help on the tangent function, type
help tan
18
Built-in function
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• Common Computations
19
ELEMENTARY MATH FUNCTIONS
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• As a rule, the function log in all computer languages means
the natural logarithm .
• If you want logarithms to the base 10, you’ll need to use the
log10 function.
• The mathematical notation and MATLAB ® syntax for raising e
to a power are not the same. To raise e to the third power, the
mathematical notation would be e3.
• However, the MATLAB ® syntax is exp(3) .
20
Built-in function
Dr. Manish K Rathod, Assistant Professor, MED, Surat
21
Rounding functions
For example, suppose you want to buy apples at the grocery store. The apples
cost 15 Rs. a piece. You have 55 Rs. How many apples can you buy?
fix (55/15)
ans =
3
Dr. Manish K Rathod, Assistant Professor, MED, Surat
22
Discrete Mathematics
Dr. Manish K Rathod, Assistant Professor, MED, Surat
23
TRIGONOMETRIC FUNCTIONS
Dr. Manish K Rathod, Assistant Professor, MED, Surat
24
DATA ANALYSIS FUNCTIONS
• max(x)
Finds the largest value in a vector x.
x[1, 5, 3];
max(x)
ans =
5
If x[1, 5, 3; 2, 4, 6];…..????
• [a,b]=max(x)
Finds both the largest value in a vector x and its location in vector x.
x[1, 5, 3];
[a,b]= max(x)
a =
5
b =
2
Dr. Manish K Rathod, Assistant Professor, MED, Surat
25
DATA ANALYSIS FUNCTIONS
• max(x,y)
Creates a matrix the same size as x and y. (Both x and y must
have the same number of rows and columns.) Each element in
the resulting matrix contains the maximum value from the
corresponding positions in x and y.
x[1, 5, 3; 2, 4, 6]; y[10,2,4; 1, 8, 7];
max(x,y)
• Same as min(x);
[a,b]=min(x);
min(x,y)
Dr. Manish K Rathod, Assistant Professor, MED, Surat
26
DATA ANALYSIS FUNCTIONS
• sum(x)
Sums the elements in vector x.
• prod(x)
Computes the product of the
elements of a vector x.
• sort(x)
sorting the elements
• diff(x)
differences between
adjacent elements
Dr. Manish K Rathod, Assistant Professor, MED, Surat
27
DATA ANALYSIS FUNCTIONS
• cumsum(x)
Computes a vector of the same size as, and containing
cumulative sums of the elements of, a vector x.
For example, if x = [1 5 3], the resulting vector is x=[1 6 9].
• cumprod(x)
Computes a vector of the same size as, and containing
cumulative products of the elements of, a vector x .
For example, if x = [1 5 3], the resulting vector is x=[1 5 15].
• sortrows(x,n)
Sorts the rows in a matrix on the basis of the values in column
n. If n is negative, the values are sorted in descending order. If
n is not specified, the default column used as the basis for
sorting is column 1.
Dr. Manish K Rathod, Assistant Professor, MED, Surat
28
DATA ANALYSIS FUNCTIONS
skating_results = [ 1.0000 42.0930
2.0000 42.0890
3.0000 41.9350
4.0000 42.4970
5.0000 42.0020]
>> sortrows(skating_results)
>> sortrows(skating_results,2)
>> sortrows(skating_results,-2)
Dr. Manish K Rathod, Assistant Professor, MED, Surat
29
Special function
Dr. Manish K Rathod, Assistant Professor, MED, Surat
30
User defined function
• A company requires some of its assembly drawings are to be drawn by an
AutoCad operator as an out side party
– Main program ‘Company’ performs the task of doing assembly drawing
• Calls an AutoCad operator, explains the drawing and the details of parts
– Main program ‘Company’ requires a function name ‘AutoCad_Operator’
• Company also provides operator with a zerox copy of drawing of all the parts
– Program ‘Company’ supplies a copy of all details (i. e. variables) to
function ‘AutoCad_Operator’, any modification by ‘AutoCad_Operator’ in
the drawing will not affect the performance of company.
• Company fixes the date and wait for completion of consignment
– Program ‘Company’ waits for the ‘AutoCad_Operator’ to complete job
• Company gets work done in time in the form of an assembly drawing
– Main program ‘Company’ gets work done from function name
‘AutoCad_Operator’ in the form of an assembly drawing, without
submitting the zerox he received by the ‘Company’, which he may destroy.
Dr. Manish K Rathod, Assistant Professor, MED, Surat
31
User defined function
• A function file is also an M-file, like a script file, except that the
variables in a function file are all local .
• Both built-in MATLAB® functions and user-defined MATLAB®
functions have the same structure. Each consists of a name, user-
provided input, and calculated output.
• For example, the function cos(x)
• is named cos ,
• takes the user input inside the parentheses (in this case, x ), and
• calculates a result.
• The user does not see the calculations performed, but just accepts
the answer.
Dr. Manish K Rathod, Assistant Professor, MED, Surat
32
User defined function
• Imagine that you have created a function called my_function .
Using my_function(x)
• in a program or from the command window will return a
result, as long as x is defined and the logic in the function
definition works.
• User-defined functions are created in M-files. Each must start
with a function definition line that contains:
• The word ‘function’
• A variable that defines the function output
• A function name
• A variable used for the input argument
Dr. Manish K Rathod, Assistant Professor, MED, Surat
33
User defined function
• For example,
function [output variables] = my_function(x)
• The first word, function, is mandatory, and tells MATLAB this m-
file in a function file.
• On the lefthand side of the equals sign is a list of the output
variables that the function will return. When there is more than
one output variable, then they are enclosed in square brackets.
• On the righthand side of the equals sign is the name of the
function. The name used to save a function file must match the
function name.
• Lastly, within the round brackets after the function name, is a
comma separated list of the input variables.
Dr. Manish K Rathod, Assistant Professor, MED, Surat
User defined function
Dr. Manish K Rathod, Assistant Professor, MED, Surat 34
35
User defined function
• It is good practice to put some comments after the function
definition line to explain what task the function performs and
how you should use the input and output variables.
Dr. Manish K Rathod, Assistant Professor, MED, Surat
36
User defined function
When x and y are defined in the command window and the function g is called, a
vector of output values is returned:
Dr. Manish K Rathod, Assistant Professor, MED, Surat
37
User defined function
When x and y are defined in the command window and the function g is called, a
vector of output values is returned:
Dr. Manish K Rathod, Assistant Professor, MED, Surat
38
User defined function
• You can also create functions that return more than one output
variable. Make the output a matrix of answers instead of a single
variable
function [dist, vel, accel] = motion(t)
% This function calculates the distance, velocity, and
% acceleration of a particular car for a given value of t
% assuming all 3 parameters are initially 0.
accel = 0.5 .*t;
vel = t.^2/4;
dist = t.^3/12;
• Once saved as motion in the current folder, you can use the
function to find values of distance , velocity , and acceleration at
specified times:
Dr. Manish K Rathod, Assistant Professor, MED, Surat
39
User defined function
[distance, velocity, acceleration] = motion(10)
distance =
83.33
velocity =
25
acceleration =
5
• If you call the motion function without specifying all three outputs,
only the first output will be returned:
motion(10)
ans =
83.333
Dr. Manish K Rathod, Assistant Professor, MED, Surat
40
User defined function
• EXAMPLE
• Produce a conversion table for Celsius and Fahrenheit
temperatures.
• The input to the function should be two numbers: Tlower and Tupper
which define the lower and upper range, in Celsius, for the table.
• The output of the function should be a two column matrix with
the first column showing the temperature in Celsius, from Tlower
and Tupper with an increment of 1 C, and the second column
showing the corresponding temperature in Fahrenheit.
Dr. Manish K Rathod, Assistant Professor, MED, Surat
A user interface is the point of contract or method
of interactions between a person and a computer
or computer program.
A Graphical user interface, or GUI is a user interface
incorporating graphical objects such as window , icons,
buttons, menus, and text.
The user communicates with the computer using input
devices such as a keyboard, mouse, trackball, drawing
pad, and microphone.
GRAPHICAL USER INTERFACE
Dr. Manish K Rathod, Assistant Professor, MED, Surat 41
Some well known GUI’s
WORD, Network Configuration and Control Panel offer functionality for
controlling the computer and data without need for system level commands
and scripts. Most operations on data can be done with icon presses.
Dr. Manish K Rathod, Assistant Professor, MED, Surat 42
Some simple interface commands
Simplest user interface command is the message
box. This is common in Windows programs and
VB. Matlab msgbox is configured as follows.
The result of calling this in the command line is a
little box with a message displayed and a single
‘ok’ button that clears the box. 43
As you can imagine you could use the msgbox to output
the result of your program.
Ie.
Some simple interface commands
44
An error message
• an error message
• Errordlg(‘string’,’DBName’)
errordlg('you got that wrong','error message')
Dr. Manish K Rathod, Assistant Professor, MED, Surat 45
Questdlg
It provides a question and a series of possible
answers. The user presses a key and that key
name is returned from the questdlg function. The
example below uses switch to effect an operation
based on the choice.
%syntax
%ButtonName=questdlg(Question,Title
,Btn1,Btn2,OPTIONS);
46
Questdlg
47
• Print dlg Box:-
• Syntax:- printdlg
printdlg prints the current figure.
48
• Help dlg Box:
• Syntax:- helpdlg('helpstring')
helpdlg('helpstring','dlgname')
• helpdlg('helpstring')
displays a dialog box named 'Help Dialog'
containing the string specified by
'helpstring'.
• helpdlg('helpstring','dlgname')
displays a dialog box named 'dlgname'
containing the string 'helpstring'
Dr. Manish K Rathod, Assistant Professor, MED, Surat 49
• Example:-
helpdlg('Choose 10 points from the
figure','Point Selection');
Dr. Manish K Rathod, Assistant Professor, MED, Surat 50
MATLAB – Graphics Capability (Plots)
Mechanical Engineering Department
Sardar Vallabhbhai National Institute of Technology, Surat,
Gujarat, India.
mkr@med.svnit.ac.in
Dr. Manish K Rathod
51
x a b
10 1 2
15 3 4
25 5 8
32 7 11
Introduction - plot
0
2
4
6
8
10
12
0 5 10 15 20 25 30 35
Series1
Series2
Dr. Manish K Rathod, Assistant Professor, MED, Surat 52
• Large tables of data are difficult to interpret.
• Engineers use graphing techniques to make the
information easier to understand.
• With a graph, it is easy to identify trends, pick out
highs and lows, and isolate data points that may be
measurement or calculation errors.
• Graphs can also be used as a quick check to
determine whether a computer solution is yielding
expected results.
Introduction - plot
Dr. Manish K Rathod, Assistant Professor, MED, Surat 53
OBJECTIVE
• Create and label two dimensional plots
• Adjust the appearance of your plots
• Divide the plotting window into subplots
• Use the interactive MATLAB ® plotting tools
Dr. Manish K Rathod, Assistant Professor, MED, Surat 54
55
Introduction - plot
linear plots
line plots
logarithmic plots on both scales
logarithmic plots on one scale
stem plots
bar graphs
three-dimensional plots
MATLAB has the capability to generate plots of many types.
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• The xy plot is the most commonly used plot
by engineers
• The independent variable is usually called x
• The dependent variable is usually called y
56
Two Dimensional Plots
A very important fact that should be emphasized at the outset is
that to plot one vector against another, the vectors must have
the same number of elements.
One can plot either a column vector or a row vector versus either
a column vector or a row vector provided they have the same
number of values.
Dr. Manish K Rathod, Assistant Professor, MED, Surat
57
•If the vectors have different lengths, it is possible to
use a portion of the longer one as one of the
variables.
•For example, suppose y has 200 values and x has
120 values. One could define y1 by the following
command:
>> y1 = y(1:120)
•The variable y1 now has the same number of
points as x and the two could be plotted together.
Two Dimensional Plots
Dr. Manish K Rathod, Assistant Professor, MED, Surat
Command for producing a simple plot is
plot (x values, y values, 'style-options’)
x values and y values – Vector
Style-option - Optional argument
Creating a plot
Dr. Manish K Rathod, Assistant Professor, MED, Surat 58
59
Time, sec Distance, Ft
0 0
2 0.33
4 4.13
6 6.29
8 6.85
10 11.19
12 13.19
14 13.96
16 16.33
18 18.17
Time is the independent
variable and distance is
the dependent variable
example
Dr. Manish K Rathod, Assistant Professor, MED, Surat
Define x and y and call the plot function
60
Any variable name that is convenient for the dependent and independent
variables can be used.
time, sec Distance,
Ft
0 0
1 0.33
3 4.13
5 6.29
7 6.85
9 11.19
11 13.19
13 13.96
15 16.33
17 18.17
example
Dr. Manish K Rathod, Assistant Professor, MED, Surat
61
Once the plot command is executed, the Figure Window opens with the following
plot.
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• If the plot command with a single matrix is used,
MATLAB plots the values versus the index number
• Usually this type of data is plotted on a bar graph
• When plotted on an xy grid, it is often called a line
graph.
62
Variations
Dr. Manish K Rathod, Assistant Professor, MED, Surat
LINE SPECIFIERS IN THE plot() COMMAND
Line specifiers can be added in the plot command to:
 Specify the style of the line.
 Specify the color of the line.
 Specify the type of the markers (if markers are desired).
plot(x,y,’line specifiers’)
Dr. Manish K Rathod, Assistant Professor, MED, Surat 63
LINE SPECIFIERS IN THE plot() COMMAND
• The appearance of the plots by selecting user defined can be
changed
– line styles
– color
– mark styles
• Try using “help plot” for a list of available styles
Dr. Manish K Rathod, Assistant Professor, MED, Surat 64
 The specifiers are typed inside the plot() command as strings.
 Within the string the specifiers can be typed in any order.
 The specifiers are optional. This means that none, one, two, or all the three
can be included in a command.
EXAMPLES:
plot(x,y) A solid blue line connects the points with no markers.
plot(x,y,’r’) A solid red line connects the points with no markers.
plot(x,y,’--y’) A yellow dashed line connects the points.
plot(x,y,’*’) The points are marked with * (no line between the points)
plot(x,y,’g:d’) A green dotted line connects the points which are
marked with diamond markers.
LINE SPECIFIERS IN THE plot() COMMAND
Dr. Manish K Rathod, Assistant Professor, MED, Surat 65
Table 5. 2 Line, Mark and Color Options
Line Type Indicator Point Type Indicato
r
Color Indicator
solid - point . blue b
dotted : circle o green g
dash-dot -. x-mark x red r
dashed -- plus + cyan c
star * magenta m
square s yellow y
diamond d black k
triangle
down
v
triangle up ^
triangle left <
triangle
right
>
pentagram p
hexagram h
LINE SPECIFIERS IN THE plot() COMMAND
Dr. Manish K Rathod, Assistant Professor, MED, Surat 66
Year
Sales (M)
1988 1989 1990 1991 1992 1993 1994
127 130 136 145 158 178 211
>> year = [1988:1:1994];
>> sales = [127, 130, 136, 145, 158, 178, 211];
>> plot(year,sales,'--r*')
Line Specifiers:
dashed red line and
asterisk markers.
LINE SPECIFIERS IN THE plot() COMMAND
Dr. Manish K Rathod, Assistant Professor, MED, Surat 67
Dashed red line and
asterisk markers.
LINE SPECIFIERS IN THE plot() COMMAND
Dr. Manish K Rathod, Assistant Professor, MED, Surat 68
plot(x,y,':ok')
• In this command
– the : means use a dotted line
– the o means use a circle to mark each point
– the letter k indicates that the graph should
be drawn in black
69
LINE SPECIFIERS IN THE plot() COMMAND
Dr. Manish K Rathod, Assistant Professor, MED, Surat
70
dotted line
circles
black
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• MATLAB overwrites the figure window every
time you request a new plot
• To open a new figure window use the figure
function – for example
figure(2)
71
Creating Multiple Plots
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• hold on
– Freezes the current plot, so that an additional plot
can be overlaid
• When you use this approach the additional line is
drawn in blue – the default drawing color
72
MULTIPLE GRAPHS IN A SAME PLOT
The first plot is drawn in blue
Dr. Manish K Rathod, Assistant Professor, MED, Surat
73
The hold on command
freezes the plot
The second line
is also drawn in
blue, on top of
the original plot
The second line
is also drawn in
blue, on top of
the original plot
Dr. Manish K Rathod, Assistant Professor, MED, Surat
Using hold command
Invoking hold on at any
point freezes the plot in the
graphics window
Subsequent plots are added
to existing plot
Dr. Manish K Rathod, Assistant Professor, MED, Surat 74
Dr. Manish K Rathod, Assistant Professor, MED, Surat 75
• Multiple lines on a single graph with one command
can also be created.
76
MULTIPLE GRAPHS IN A SAME PLOT
Plots three graphs in the same plot:
yversus x, vversus u, and hversus t.
 By default, MATLAB makes the curves in different colors.
 Additional curves can be added.
 The curves can have a specific style by adding specifiers after each pair, for
example:
plot(x,y,u,v,t,h)
plot(x,y,’-b’,u,v,’—r’,t,h,’g:’)
Dr. Manish K Rathod, Assistant Professor, MED, Surat
4
2 

 x
Plot of the function, and its first and second derivatives, for
, all in the same plot.
10
26
3 3


 x
x
y
4
2 

 x
x = [-2:0.01:4];
y = 3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd = 18*x;
plot(x,y,'-b',x,yd,'--r',x,ydd,':k')
vector x with the domain of the function.
Vector y with the function value at each x.
4
2 

 x
Vector yd with values of the first derivative.
Vector ydd with values of the second derivative.
Create three graphs, y vs. x (solid blue line), yd vs.
x (dashed red line), and ydd vs. x (dotted black
line) in the same figure.
MULTIPLE GRAPHS IN A SAME PLOT
Dr. Manish K Rathod, Assistant Professor, MED, Surat 77
-2 -1 0 1 2 3 4
-40
-20
0
20
40
60
80
100
120
USING THE plot() COMMAND TO PLOT
MULTIPLE GRAPHS IN THE SAME PLOT
Dr. Manish K Rathod, Assistant Professor, MED, Surat 78
FORMATTING PLOTS
A plot can be formatted to have a required appearance.
With formatting you can:
 Add title to the plot.
 Add labels to axes.
 Change range of the axes.
 Add legend.
 Add text blocks.
 Add grid.
Dr. Manish K Rathod, Assistant Professor, MED, Surat 79
FORMATTING PLOTS
MATLAB SUPPORTS TWO WAYS TO EDIT THE PLOTS :
Using the mouse to select and edit objects interactively
(Interactive Plot Editing)
Using MATLAB functions at command-line or in an M-file
(Using Functions to Edit Graphs)
Dr. Manish K Rathod, Assistant Professor, MED, Surat 80
FORMATTING COMMANDS
title(‘string’)
Adds the string as a title at the top of the plot.
xlabel(‘string’)
Adds the string as a label to the x-axis.
ylabel(‘string’)
Adds the string as a label to the y-axis.
axis([xmin xmax ymin ymax])
Sets the minimum and maximum limits of the x- and y-axes.
Dr. Manish K Rathod, Assistant Professor, MED, Surat 81
FORMATTING COMMANDS
Creates a legend using the strings to label various curves (when several
curves are in one plot). The location of the legend is specified by the mouse.
legend(‘string1’,’string2’,’string3’)
text(x,y,’string’)
Places the string (text) on the plot at coordinate x,y
relative to the plot axes.
gtext(‘string’)
Places the string (text) on the plot. When the
command executes the figure window pops and the
text location is clicked with the mouse.
Dr. Manish K Rathod, Assistant Professor, MED, Surat 82
 legend (…., pos) :
pos = -1 places the legend outside the axes boundary on the right
side.
pos = 0 places the legend inside the axes boundary, obscuring as
few points as possible.
pos = 1 places the legend in the upper-right corner of the axes
(default).
pos = 2 places legend in the upper-left corner of axes.
pos = 3 places legend in the lower-left corner of axes.
pos = 4 places legend in the lower-right corner of axes.
 legend off: deletes the legend from plot
FORMATTING COMMANDS
Dr. Manish K Rathod, Assistant Professor, MED, Surat 83
-1
0
1
3 4
Dr. Manish K Rathod, Assistant Professor, MED, Surat 84
EXAMPLE OF A FORMATTED PLOT
Below is a script file of the formatted light intensity plot
x=[10:0.1:22];
y=95000./x.^2;
xd=[10:2:22];
yd=[950 640 460 340 250 180 140];
plot(x,y,'-','LineWidth',1.0)
hold on
plot(xd,yd,'ro--',‘LineWidth',1.0,'markersize',10)
hold off
Creating a vector with light
intensity from data.
Creating a vector with coordinates of data points.
Creating vector x for plotting the theoretical curve.
Creating vector y for plotting the theoretical curve.
Dr. Manish K Rathod, Assistant Professor, MED, Surat 85
EXAMPLE OF A FORMATTED PLOT
Formatting of the light intensity plot (cont.)
xlabel('DISTANCE (cm)')
ylabel('INTENSITY (lux)')
title('fontname{Arial}Light Intensity as a Function of Distance','FontSize',14)
axis([8 24 0 1200])
text(14,700,'Comparison between theory and
experiment.','EdgeColor','r','LineWidth',2)
legend('Theory','Experiment',0)
Creating text.
Creating a legend.
Title for the plot.
Setting limits of the axes.
Labels for the axes.
The plot that is obtained is shown again in the next slide.
Dr. Manish K Rathod, Assistant Professor, MED, Surat 86
EXAMPLE OF A FORMATTED PLOT
Dr. Manish K Rathod, Assistant Professor, MED, Surat 87
88
Dr. Manish K Rathod, Assistant Professor, MED, Surat
You can use Greek letters in your labels by putting a
backslash () before the name of the letter.
For example:
title(‘alpha beta gamma’)
creates the plot title α β γ
To create a superscript use curly brackets
title(‘x^{2}’) Gives x2
89
IMPROVING LABELS
Dr. Manish K Rathod, Assistant Professor, MED, Surat
FORMATTING A PLOT IN THE FIGURE WINDOW
Once a figure window is open, the figure can be formatted interactively.
Use Figure, Axes,
and Current
Object-Properties
in the Edit menu
Click here to start the plot
edit mode.
Use the insert menu to
Dr. Manish K Rathod, Assistant Professor, MED, Surat 90
FORMATTING A PLOT IN THE FIGURE WINDOW
Dr. Manish K Rathod, Assistant Professor, MED, Surat 91
FORMATTING A PLOT IN THE FIGURE WINDOW
Dr. Manish K Rathod, Assistant Professor, MED, Surat 92
SAVING A FIGURE
Save from File menu saves the a figure
To save figure using a graphics format
(*.bmp,*.jpg, etc) , select Export from
the File menu
Dr. Manish K Rathod, Assistant Professor, MED, Surat 93
Subplots
94
• The subplot command allows to subdivide the
graphing window into a grid of m rows and n
columns
• subplot(m,n,p)
rows columns location
2 rows
2 columns
1 2
3 4
-2
0
2
-2
0
2
-5
0
5
x
Peaks
y
subplot(2,2,1)
Dr. Manish K Rathod, Assistant Professor, MED, Surat
95
2 rows and 1 column
Subplots
Dr. Manish K Rathod, Assistant Professor, MED, Surat
Other Types of 2-D Plots
• Polar Plots
• Logarithmic Plots
• Bar Graphs
• Pie Charts
• Histograms
• X-Y graphs with 2 y axes
• Function Plots
96
MATLAB supports a variety of graph types that enable to present information
effectively. The type of graph selected depends, to a large extent on the nature
of the data
Dr. Manish K Rathod, Assistant Professor, MED, Surat
Logarithmic Plots
• A logarithmic scale (base 10) is convenient when
– a variable ranges over many orders of magnitude, because
the wide range of values can be graphed, without
compressing the smaller values.
– data varies exponentially.
• plot – uses a linear scale on both axes
• semilogy – uses a log10 scale on the y axis
• semilogx – uses a log10 scale on the x axis
• loglog – use a log10 scale on both axes
97
Dr. Manish K Rathod, Assistant Professor, MED, Surat
98
Logarithmic Plots
Dr. Manish K Rathod, Assistant Professor, MED, Surat
99
Logarithmic Plots
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• Bar graphs are useful to view results over
time, comparing results, and displaying
individual contribution to a total amount.
• Pie charts show individual contribution to a
total amount.
• Histograms show the distribution of data
values.
Bar Graphs and Pie Charts
Dr. Manish K Rathod, Assistant Professor, MED, Surat 100
Bar Graphs and Pie Charts
• MATLAB includes a whole family of bar graphs and
pie charts
– bar(x) – vertical bar graph
– barh(x) – horizontal bar graph
– bar3(x) – 3-D vertical bar graph
– bar3h(x) – 3-D horizontal bar graph
– pie(x) – pie chart
– pie3(x) – 3-D pie chart
101
Dr. Manish K Rathod, Assistant Professor, MED, Surat
102
Dr. Manish K Rathod, Assistant Professor, MED, Surat
103
Dr. Manish K Rathod, Assistant Professor, MED, Surat
Histograms
• A histogram is a plot showing the distribution
of a set of values
104
Dr. Manish K Rathod, Assistant Professor, MED, Surat
Stem and stair step plots
display discrete data.
Stem and Stair
105
Polar Plots
• Some functions are easier to specify using
polar coordinates than by using rectangular
coordinates
• For example the equation of a circle is
– y=sin(x) in polar coordinates
106
Dr. Manish K Rathod, Assistant Professor, MED, Surat
107
Dr. Manish K Rathod, Assistant Professor, MED, Surat
X-Y Graphs with Two Y Axes
• Scaling Depends on the largest value plotted
• Its difficult to see how the blue line behaves, because
the scale isn’t appropriate
108
Dr. Manish K Rathod, Assistant Professor, MED, Surat
109
The plotyy function
allows you to use two
scales on a single
graph
X-Y Graphs with Two Y Axes
Dr. Manish K Rathod, Assistant Professor, MED, Surat
Function Plots
110
• Function plots allow you to use a function as
input to a plot command, instead of a set of
ordered pairs of x-y values
• fplot('sin(x)',[-2*pi,2*pi])
function input as a
string
range of the independent
variable – in this case x
Dr. Manish K Rathod, Assistant Professor, MED, Surat
111
Function Plots
Dr. Manish K Rathod, Assistant Professor, MED, Surat
• Compass, feather, and quiver plots display
direction and velocity vectors.
• Contour plots show equivalued regions in
data.
• Interactive plotting enable to select data
points to plot with the pointer.
Other Plots
Dr. Manish K Rathod, Assistant Professor, MED, Surat 112
3 D Graphs
Elementary 3-D plots
• plot3 - Plot lines and points in 3-D space.
• mesh - 3-D mesh surface.
• surf - 3-D colored surface.
• fill3 - Filled 3-D polygons.
plot3(x,y,z) - generates a line in 3-space through the
points whose coordinates are the elements of x, y, z.
Dr. Manish K Rathod, Assistant Professor, MED, Surat 113
• These plots require a set of order triples ( x-y-z values) as input
114
The z-axis is labeled the
same way the x and y
axes are labeled
3 D Graphs
Dr. Manish K Rathod, Assistant Professor, MED, Surat
115
MATLAB uses a
coordinate
system
consistent with
the right hand
rule
3 D Graphs
Dr. Manish K Rathod, Assistant Professor, MED, Surat
3 D Graphs
116
3 D Graphs
117
Creating a grid in the x-y plane:
X and Y are the matrix of the x and y
coordinates of the grid points
respectively.
x and y are vectors that divides the
domain of the x and y respectively.
(-1,1)
(-1,4) (3,4)
(3,1)
3 D Graphs
Dr. Manish K Rathod, Assistant Professor, MED, Surat 118
For Example, if
z=xy2/(x2 + y2)
The value of z at
each point of the
grid is calculated
3 D Graphs
Dr. Manish K Rathod, Assistant Professor, MED, Surat 119
3 D Graphs
120
• Controls the direction from which the plot is
viewed.
• Done by specifying a direction in terms of
azimuth and elevation angles.
• View (az,el) or view([az,el])
Angle in the x-y plane measured
relative to the negative y axis
direction and positive in counter
clockwise direction
Angle of elevation from
x-y plane.
3 D Graphs - View Command
Dr. Manish K Rathod, Assistant Professor, MED, Surat 121
3 D Graphs - View Command
122
Printing the Figure
 using option Print under File menu
 using print command
 The Export option under File menu to
export figure to a variety of standard
graphics file format
 Using print command
Dr. Manish K Rathod, Assistant Professor, MED, Surat 123
Dr. Manish K Rathod, Assistant Professor, MED, Surat 124

More Related Content

Similar to Getting_Start_MATLAB_BVM1.pptx

Bca winter 2013 2nd sem
Bca winter 2013 2nd semBca winter 2013 2nd sem
Bca winter 2013 2nd sem
smumbahelp
 
Mathcad presentation
Mathcad presentationMathcad presentation
Mathcad presentation
karam albarody
 
Transfer Learning for Improving Model Predictions in Highly Configurable Soft...
Transfer Learning for Improving Model Predictions in Highly Configurable Soft...Transfer Learning for Improving Model Predictions in Highly Configurable Soft...
Transfer Learning for Improving Model Predictions in Highly Configurable Soft...
Pooyan Jamshidi
 
A practical work of matlab
A practical work of matlabA practical work of matlab
A practical work of matlab
SalanSD
 
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdfComputer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
PranavAnil9
 
Matlab Manual
Matlab ManualMatlab Manual
R programmingmilano
R programmingmilanoR programmingmilano
R programmingmilano
Ismail Seyrik
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
valerie5142000
 
Cse 7 softcomputing lab
Cse 7 softcomputing labCse 7 softcomputing lab
Cse 7 softcomputing lab
Vivek Kumar Sinha
 
Analytics Boot Camp - Slides
Analytics Boot Camp - SlidesAnalytics Boot Camp - Slides
Analytics Boot Camp - Slides
Aditya Joshi
 
Lec1
Lec1Lec1
Lec1
Lec1Lec1
Lec1
Saad Gabr
 
SPSS-SYNTAX
SPSS-SYNTAXSPSS-SYNTAX
SPSS-SYNTAX
D Dutta Roy
 
Matlab Tutorial.ppt
Matlab Tutorial.pptMatlab Tutorial.ppt
Matlab Tutorial.ppt
RaviMuthamala1
 
function (mal120) By Wakil Kumar
function (mal120) By Wakil Kumarfunction (mal120) By Wakil Kumar
function (mal120) By Wakil Kumar
Wakil Kumar
 
Lecture#1(Algorithmic Notations).ppt
Lecture#1(Algorithmic Notations).pptLecture#1(Algorithmic Notations).ppt
Lecture#1(Algorithmic Notations).ppt
MuhammadTalhaAwan1
 
Base sas interview questions
Base sas interview questionsBase sas interview questions
Base sas interview questions
Dr P Deepak
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
Vinay Kumar
 
Programming in python
Programming in pythonProgramming in python
Programming in python
Ivan Rojas
 
D05511625
D05511625D05511625
D05511625
IOSR-JEN
 

Similar to Getting_Start_MATLAB_BVM1.pptx (20)

Bca winter 2013 2nd sem
Bca winter 2013 2nd semBca winter 2013 2nd sem
Bca winter 2013 2nd sem
 
Mathcad presentation
Mathcad presentationMathcad presentation
Mathcad presentation
 
Transfer Learning for Improving Model Predictions in Highly Configurable Soft...
Transfer Learning for Improving Model Predictions in Highly Configurable Soft...Transfer Learning for Improving Model Predictions in Highly Configurable Soft...
Transfer Learning for Improving Model Predictions in Highly Configurable Soft...
 
A practical work of matlab
A practical work of matlabA practical work of matlab
A practical work of matlab
 
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdfComputer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
 
Matlab Manual
Matlab ManualMatlab Manual
Matlab Manual
 
R programmingmilano
R programmingmilanoR programmingmilano
R programmingmilano
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
 
Cse 7 softcomputing lab
Cse 7 softcomputing labCse 7 softcomputing lab
Cse 7 softcomputing lab
 
Analytics Boot Camp - Slides
Analytics Boot Camp - SlidesAnalytics Boot Camp - Slides
Analytics Boot Camp - Slides
 
Lec1
Lec1Lec1
Lec1
 
Lec1
Lec1Lec1
Lec1
 
SPSS-SYNTAX
SPSS-SYNTAXSPSS-SYNTAX
SPSS-SYNTAX
 
Matlab Tutorial.ppt
Matlab Tutorial.pptMatlab Tutorial.ppt
Matlab Tutorial.ppt
 
function (mal120) By Wakil Kumar
function (mal120) By Wakil Kumarfunction (mal120) By Wakil Kumar
function (mal120) By Wakil Kumar
 
Lecture#1(Algorithmic Notations).ppt
Lecture#1(Algorithmic Notations).pptLecture#1(Algorithmic Notations).ppt
Lecture#1(Algorithmic Notations).ppt
 
Base sas interview questions
Base sas interview questionsBase sas interview questions
Base sas interview questions
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
 
Programming in python
Programming in pythonProgramming in python
Programming in python
 
D05511625
D05511625D05511625
D05511625
 

Recently uploaded

Gas agency management system project report.pdf
Gas agency management system project report.pdfGas agency management system project report.pdf
Gas agency management system project report.pdf
Kamal Acharya
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
mahaffeycheryld
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
AjmalKhan50578
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
harshapolam10
 
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
PIMR BHOPAL
 
morris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdfmorris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdf
ycwu0509
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
bjmsejournal
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
Prakhyath Rai
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
Paris Salesforce Developer Group
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 

Recently uploaded (20)

Gas agency management system project report.pdf
Gas agency management system project report.pdfGas agency management system project report.pdf
Gas agency management system project report.pdf
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
 
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
 
morris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdfmorris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdf
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 

Getting_Start_MATLAB_BVM1.pptx

  • 1. MATLAB – Selection and Repetition Structure Mechanical Engineering Department Sardar Vallabhbhai National Institute of Technology, Surat, Gujarat, India. mkr@med.svnit.ac.in Dr. Manish K Rathod 1
  • 2.  It is developed by The Mathworks, Inc. (http://www.mathworks.com) • It is an integrated technical computing environment that combines numeric computation, advanced graphics and visualization, and a high-level programming language. – Interpreted language – Scientific programming environment – Very good tool for the manipulation of matrices – Great visualisation capabilities – Loads of built-in functions – Easy to learn and simple to use – slow (compared with FORTRAN or C) because it is interpreted. – automatic memory management; no need to declare arrays. What is MATrix LABoratory ? Dr. Manish K Rathod, Assistant Professor, MED, SVNIT, Surat 2
  • 3. Dr. Manish K Rathod, Assistant Professor, MED, SVNIT, Surat 3
  • 4. vast collection of computational algorithms ranging from elementary functions to more sophisticated functions high-level matrix/array language with Control flow statements, functions, data structures, input/output, and object-oriented programming features. Mathematical Function Library MATLAB Language Dr. Manish K Rathod, Assistant Professor, MED, SVNIT, Surat 4
  • 5. 5 Computer program • One way to think of a computer program (not just MATLAB®) is to consider how the statements that compose it are organized. • Usually, sections of computer code can be categorized as sequences , selection structures , and repetition structures. Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 6. Computer program Sequence • List of commands that are executed one after another. Selection Structure • Allows the programmer to execute one / more commands if some criterion is true and a second command if the criterion is false. Repetition Structure • A group of statements to be executed multiple times. • Depends on either a counter or the evaluation of a logical condition. Dr. Manish K Rathod, Assistant Professor, MED, Surat 6
  • 7. • Plan your program – Two common approach • Graphical approach (Flowchart) • Verbal description (Pseudocode) • For simple program, Psdeudocode is best. – Outline a set of statements describing the steps to solve a problem – Convert these steps into an M-file using appropriate code Flowchart and pseudo code Dr. Manish K Rathod, Assistant Professor, MED, Surat 7
  • 8. 1. Wake-up at 7:00 a.m., except Sunday 2. Get ready and reach office before 8:45 a.m. 3. If it is late; take auto, else go by bus 4. Work from 9.00 a.m. to 12.00 a.m. 5. Go to lunch for all days except fast 6. Between 4:00 p.m. to 6:00 p.m. conduct Weekly Meeting Marketing meeting on Mon, Wed, Fri and Production meeting on Tue, Thu, Sat 7. On every 1st , check for salary & release important dues 8. Go back to residence Schedule of an executive Dr. Manish K Rathod, Assistant Professor, MED, Surat 8
  • 9. Read Time, Day and Date from watch & calendar For Day == Mon, Tue, Wed, Thu, Fri and Sat if (Time > or = 7:00), wake-up (brake) else go to sleep and check again after some time % Get ready and reach office before 8:45 while not reached in office hurry up!!! if it is late; pickup an auto, (i.e. Time > or = 8:00) else wait for bus until bus arrives while Time < or = 12:00 work in office (from 9.00 to 12.00) while (Time == 12:00) & (NOT fast) go to lunch end while Time ~= 4:00 work in office (from 12.00 to 4.00 PM) if (Day == Mon) or (Day == Wed) or (Day == Fri) Conduct Marketing Meeting, end at 6:00 if (Day == Tue) or (Day == Thu) or (Day == Sat) Conduct Production Meeting, end at 6:00 if Date == 1st Get salary and release important dues Go back to residence and end the day Schedule of an executive (pseudo-code) Dr. Manish K Rathod, Assistant Professor, MED, Surat 9
  • 10. MATLAB Functions - Basic Features Mechanical Engineering Department Sardar Vallabhbhai National Institute of Technology, Surat, Gujarat, India. mkr@med.svnit.ac.in Dr. Manish K Rathod 10
  • 11. • Programming often requires repeating a set of tasks over and over again. • For example, the sin function in MATLAB is a set of tasks (i.e., mathematical operations) that computes an approximation for sin(x). • Rather than having to retype or copy these instructions every time you want to use the sin function, it is useful to store this sequence of instruction as a function that you can call over and over again. 11 Motivations Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 12. • A function is a group of statements that together perform a task. In MATLAB, functions are defined in separate files. • MATLAB functions are similar to C functions or Fortran subroutines. • Two types: Inbuilt Functions and, User Defined Function 12 Motivations Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 13. • You decide to paint your house by some one (which you also can do) – Main code can perform the required task but for the simplicity outside party is preferred • Identifying someone who can do this – Give a name and write a separate file • Giving possession of the house to him/them – Command of the program will be shifted to the function • Providing them with required material (color containers, brush, etc) – Submit your variable to function from your control to there control this may required that variable will be identified by different name • Observe successful completion of task – Halt the main program execution till your function will executed • Get cleaned the floor and other parts of house & take possession – Delete all the variable & workspace generated by function & get control back • Pay the persons and send off them – Spend required CPU time and terminate the function call 13 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 14. • MATLAB® has an extensive library of built-in functions to allow to perform mathematical functions, including logarithms, trigonometric functions, and statistical analysis functions. • Many of the names for MATLAB® ’s built-in functions are the same as those defined not only in the C programming language, but in Fortran and Java as well. For example, • To take the square root of the variable x , b = sqrt(x) • A big advantage of MATLAB ® is that function arguments can generally be either scalars or matrices. 14 Built-in function Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 15. All functions can be thought of as having three components: a name, input, and output. • In the preceding example, the name of the function is sqrt , the required input (also called the argument) goes inside the parentheses and can be a scalar or a matrix, and the output is a calculated value or values. Some functions require multiple inputs. • For example, the remainder function, rem , requires two inputs: a dividend and a divisor, i.e. rem(x,y) rem(10,3) %calculates the remainder of 10 divided by 3: ans = 1 15 Built-in function Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 16. • The size function is an example of a function that returns two outputs, which are stored in a single array. It determines the number of rows and columns in a matrix. Thus, d = [1, 2, 3; 4, 5, 6]; f = size(d) %returns the 1 X 2 result matrix f = 2 3 • You can also assign variable names to each of the answers by representing the left-hand side of the assignment statement as a matrix. For example, [rows,cols] = size(d) rows = 2 cols = 3 16 Built-in function Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 17. • You can create more complicated expressions by nesting functions. For instance, g = sqrt(sin(x)) • Finds the square root of the sine of whatever values are stored in the matrix named x . • If x is assigned a value of 2, x = 2; • the result is g = 0.9536 17 Built-in function Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 18. • MATLAB ® includes extensive help tools, which are especially useful in understanding how to use functions. • There are two ways to get help from within MATLAB® : – A command-line help function ( help ) and – an HTML-based set of documentation available by selecting Help from the menu bar • For example, to get help on the tangent function, type help tan 18 Built-in function Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 19. • Common Computations 19 ELEMENTARY MATH FUNCTIONS Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 20. • As a rule, the function log in all computer languages means the natural logarithm . • If you want logarithms to the base 10, you’ll need to use the log10 function. • The mathematical notation and MATLAB ® syntax for raising e to a power are not the same. To raise e to the third power, the mathematical notation would be e3. • However, the MATLAB ® syntax is exp(3) . 20 Built-in function Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 21. 21 Rounding functions For example, suppose you want to buy apples at the grocery store. The apples cost 15 Rs. a piece. You have 55 Rs. How many apples can you buy? fix (55/15) ans = 3 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 22. 22 Discrete Mathematics Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 23. 23 TRIGONOMETRIC FUNCTIONS Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 24. 24 DATA ANALYSIS FUNCTIONS • max(x) Finds the largest value in a vector x. x[1, 5, 3]; max(x) ans = 5 If x[1, 5, 3; 2, 4, 6];…..???? • [a,b]=max(x) Finds both the largest value in a vector x and its location in vector x. x[1, 5, 3]; [a,b]= max(x) a = 5 b = 2 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 25. 25 DATA ANALYSIS FUNCTIONS • max(x,y) Creates a matrix the same size as x and y. (Both x and y must have the same number of rows and columns.) Each element in the resulting matrix contains the maximum value from the corresponding positions in x and y. x[1, 5, 3; 2, 4, 6]; y[10,2,4; 1, 8, 7]; max(x,y) • Same as min(x); [a,b]=min(x); min(x,y) Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 26. 26 DATA ANALYSIS FUNCTIONS • sum(x) Sums the elements in vector x. • prod(x) Computes the product of the elements of a vector x. • sort(x) sorting the elements • diff(x) differences between adjacent elements Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 27. 27 DATA ANALYSIS FUNCTIONS • cumsum(x) Computes a vector of the same size as, and containing cumulative sums of the elements of, a vector x. For example, if x = [1 5 3], the resulting vector is x=[1 6 9]. • cumprod(x) Computes a vector of the same size as, and containing cumulative products of the elements of, a vector x . For example, if x = [1 5 3], the resulting vector is x=[1 5 15]. • sortrows(x,n) Sorts the rows in a matrix on the basis of the values in column n. If n is negative, the values are sorted in descending order. If n is not specified, the default column used as the basis for sorting is column 1. Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 28. 28 DATA ANALYSIS FUNCTIONS skating_results = [ 1.0000 42.0930 2.0000 42.0890 3.0000 41.9350 4.0000 42.4970 5.0000 42.0020] >> sortrows(skating_results) >> sortrows(skating_results,2) >> sortrows(skating_results,-2) Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 29. 29 Special function Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 30. 30 User defined function • A company requires some of its assembly drawings are to be drawn by an AutoCad operator as an out side party – Main program ‘Company’ performs the task of doing assembly drawing • Calls an AutoCad operator, explains the drawing and the details of parts – Main program ‘Company’ requires a function name ‘AutoCad_Operator’ • Company also provides operator with a zerox copy of drawing of all the parts – Program ‘Company’ supplies a copy of all details (i. e. variables) to function ‘AutoCad_Operator’, any modification by ‘AutoCad_Operator’ in the drawing will not affect the performance of company. • Company fixes the date and wait for completion of consignment – Program ‘Company’ waits for the ‘AutoCad_Operator’ to complete job • Company gets work done in time in the form of an assembly drawing – Main program ‘Company’ gets work done from function name ‘AutoCad_Operator’ in the form of an assembly drawing, without submitting the zerox he received by the ‘Company’, which he may destroy. Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 31. 31 User defined function • A function file is also an M-file, like a script file, except that the variables in a function file are all local . • Both built-in MATLAB® functions and user-defined MATLAB® functions have the same structure. Each consists of a name, user- provided input, and calculated output. • For example, the function cos(x) • is named cos , • takes the user input inside the parentheses (in this case, x ), and • calculates a result. • The user does not see the calculations performed, but just accepts the answer. Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 32. 32 User defined function • Imagine that you have created a function called my_function . Using my_function(x) • in a program or from the command window will return a result, as long as x is defined and the logic in the function definition works. • User-defined functions are created in M-files. Each must start with a function definition line that contains: • The word ‘function’ • A variable that defines the function output • A function name • A variable used for the input argument Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 33. 33 User defined function • For example, function [output variables] = my_function(x) • The first word, function, is mandatory, and tells MATLAB this m- file in a function file. • On the lefthand side of the equals sign is a list of the output variables that the function will return. When there is more than one output variable, then they are enclosed in square brackets. • On the righthand side of the equals sign is the name of the function. The name used to save a function file must match the function name. • Lastly, within the round brackets after the function name, is a comma separated list of the input variables. Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 34. User defined function Dr. Manish K Rathod, Assistant Professor, MED, Surat 34
  • 35. 35 User defined function • It is good practice to put some comments after the function definition line to explain what task the function performs and how you should use the input and output variables. Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 36. 36 User defined function When x and y are defined in the command window and the function g is called, a vector of output values is returned: Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 37. 37 User defined function When x and y are defined in the command window and the function g is called, a vector of output values is returned: Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 38. 38 User defined function • You can also create functions that return more than one output variable. Make the output a matrix of answers instead of a single variable function [dist, vel, accel] = motion(t) % This function calculates the distance, velocity, and % acceleration of a particular car for a given value of t % assuming all 3 parameters are initially 0. accel = 0.5 .*t; vel = t.^2/4; dist = t.^3/12; • Once saved as motion in the current folder, you can use the function to find values of distance , velocity , and acceleration at specified times: Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 39. 39 User defined function [distance, velocity, acceleration] = motion(10) distance = 83.33 velocity = 25 acceleration = 5 • If you call the motion function without specifying all three outputs, only the first output will be returned: motion(10) ans = 83.333 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 40. 40 User defined function • EXAMPLE • Produce a conversion table for Celsius and Fahrenheit temperatures. • The input to the function should be two numbers: Tlower and Tupper which define the lower and upper range, in Celsius, for the table. • The output of the function should be a two column matrix with the first column showing the temperature in Celsius, from Tlower and Tupper with an increment of 1 C, and the second column showing the corresponding temperature in Fahrenheit. Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 41. A user interface is the point of contract or method of interactions between a person and a computer or computer program. A Graphical user interface, or GUI is a user interface incorporating graphical objects such as window , icons, buttons, menus, and text. The user communicates with the computer using input devices such as a keyboard, mouse, trackball, drawing pad, and microphone. GRAPHICAL USER INTERFACE Dr. Manish K Rathod, Assistant Professor, MED, Surat 41
  • 42. Some well known GUI’s WORD, Network Configuration and Control Panel offer functionality for controlling the computer and data without need for system level commands and scripts. Most operations on data can be done with icon presses. Dr. Manish K Rathod, Assistant Professor, MED, Surat 42
  • 43. Some simple interface commands Simplest user interface command is the message box. This is common in Windows programs and VB. Matlab msgbox is configured as follows. The result of calling this in the command line is a little box with a message displayed and a single ‘ok’ button that clears the box. 43
  • 44. As you can imagine you could use the msgbox to output the result of your program. Ie. Some simple interface commands 44
  • 45. An error message • an error message • Errordlg(‘string’,’DBName’) errordlg('you got that wrong','error message') Dr. Manish K Rathod, Assistant Professor, MED, Surat 45
  • 46. Questdlg It provides a question and a series of possible answers. The user presses a key and that key name is returned from the questdlg function. The example below uses switch to effect an operation based on the choice. %syntax %ButtonName=questdlg(Question,Title ,Btn1,Btn2,OPTIONS); 46
  • 48. • Print dlg Box:- • Syntax:- printdlg printdlg prints the current figure. 48
  • 49. • Help dlg Box: • Syntax:- helpdlg('helpstring') helpdlg('helpstring','dlgname') • helpdlg('helpstring') displays a dialog box named 'Help Dialog' containing the string specified by 'helpstring'. • helpdlg('helpstring','dlgname') displays a dialog box named 'dlgname' containing the string 'helpstring' Dr. Manish K Rathod, Assistant Professor, MED, Surat 49
  • 50. • Example:- helpdlg('Choose 10 points from the figure','Point Selection'); Dr. Manish K Rathod, Assistant Professor, MED, Surat 50
  • 51. MATLAB – Graphics Capability (Plots) Mechanical Engineering Department Sardar Vallabhbhai National Institute of Technology, Surat, Gujarat, India. mkr@med.svnit.ac.in Dr. Manish K Rathod 51
  • 52. x a b 10 1 2 15 3 4 25 5 8 32 7 11 Introduction - plot 0 2 4 6 8 10 12 0 5 10 15 20 25 30 35 Series1 Series2 Dr. Manish K Rathod, Assistant Professor, MED, Surat 52
  • 53. • Large tables of data are difficult to interpret. • Engineers use graphing techniques to make the information easier to understand. • With a graph, it is easy to identify trends, pick out highs and lows, and isolate data points that may be measurement or calculation errors. • Graphs can also be used as a quick check to determine whether a computer solution is yielding expected results. Introduction - plot Dr. Manish K Rathod, Assistant Professor, MED, Surat 53
  • 54. OBJECTIVE • Create and label two dimensional plots • Adjust the appearance of your plots • Divide the plotting window into subplots • Use the interactive MATLAB ® plotting tools Dr. Manish K Rathod, Assistant Professor, MED, Surat 54
  • 55. 55 Introduction - plot linear plots line plots logarithmic plots on both scales logarithmic plots on one scale stem plots bar graphs three-dimensional plots MATLAB has the capability to generate plots of many types. Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 56. • The xy plot is the most commonly used plot by engineers • The independent variable is usually called x • The dependent variable is usually called y 56 Two Dimensional Plots A very important fact that should be emphasized at the outset is that to plot one vector against another, the vectors must have the same number of elements. One can plot either a column vector or a row vector versus either a column vector or a row vector provided they have the same number of values. Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 57. 57 •If the vectors have different lengths, it is possible to use a portion of the longer one as one of the variables. •For example, suppose y has 200 values and x has 120 values. One could define y1 by the following command: >> y1 = y(1:120) •The variable y1 now has the same number of points as x and the two could be plotted together. Two Dimensional Plots Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 58. Command for producing a simple plot is plot (x values, y values, 'style-options’) x values and y values – Vector Style-option - Optional argument Creating a plot Dr. Manish K Rathod, Assistant Professor, MED, Surat 58
  • 59. 59 Time, sec Distance, Ft 0 0 2 0.33 4 4.13 6 6.29 8 6.85 10 11.19 12 13.19 14 13.96 16 16.33 18 18.17 Time is the independent variable and distance is the dependent variable example Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 60. Define x and y and call the plot function 60 Any variable name that is convenient for the dependent and independent variables can be used. time, sec Distance, Ft 0 0 1 0.33 3 4.13 5 6.29 7 6.85 9 11.19 11 13.19 13 13.96 15 16.33 17 18.17 example Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 61. 61 Once the plot command is executed, the Figure Window opens with the following plot. Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 62. • If the plot command with a single matrix is used, MATLAB plots the values versus the index number • Usually this type of data is plotted on a bar graph • When plotted on an xy grid, it is often called a line graph. 62 Variations Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 63. LINE SPECIFIERS IN THE plot() COMMAND Line specifiers can be added in the plot command to:  Specify the style of the line.  Specify the color of the line.  Specify the type of the markers (if markers are desired). plot(x,y,’line specifiers’) Dr. Manish K Rathod, Assistant Professor, MED, Surat 63
  • 64. LINE SPECIFIERS IN THE plot() COMMAND • The appearance of the plots by selecting user defined can be changed – line styles – color – mark styles • Try using “help plot” for a list of available styles Dr. Manish K Rathod, Assistant Professor, MED, Surat 64
  • 65.  The specifiers are typed inside the plot() command as strings.  Within the string the specifiers can be typed in any order.  The specifiers are optional. This means that none, one, two, or all the three can be included in a command. EXAMPLES: plot(x,y) A solid blue line connects the points with no markers. plot(x,y,’r’) A solid red line connects the points with no markers. plot(x,y,’--y’) A yellow dashed line connects the points. plot(x,y,’*’) The points are marked with * (no line between the points) plot(x,y,’g:d’) A green dotted line connects the points which are marked with diamond markers. LINE SPECIFIERS IN THE plot() COMMAND Dr. Manish K Rathod, Assistant Professor, MED, Surat 65
  • 66. Table 5. 2 Line, Mark and Color Options Line Type Indicator Point Type Indicato r Color Indicator solid - point . blue b dotted : circle o green g dash-dot -. x-mark x red r dashed -- plus + cyan c star * magenta m square s yellow y diamond d black k triangle down v triangle up ^ triangle left < triangle right > pentagram p hexagram h LINE SPECIFIERS IN THE plot() COMMAND Dr. Manish K Rathod, Assistant Professor, MED, Surat 66
  • 67. Year Sales (M) 1988 1989 1990 1991 1992 1993 1994 127 130 136 145 158 178 211 >> year = [1988:1:1994]; >> sales = [127, 130, 136, 145, 158, 178, 211]; >> plot(year,sales,'--r*') Line Specifiers: dashed red line and asterisk markers. LINE SPECIFIERS IN THE plot() COMMAND Dr. Manish K Rathod, Assistant Professor, MED, Surat 67
  • 68. Dashed red line and asterisk markers. LINE SPECIFIERS IN THE plot() COMMAND Dr. Manish K Rathod, Assistant Professor, MED, Surat 68
  • 69. plot(x,y,':ok') • In this command – the : means use a dotted line – the o means use a circle to mark each point – the letter k indicates that the graph should be drawn in black 69 LINE SPECIFIERS IN THE plot() COMMAND Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 70. 70 dotted line circles black Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 71. • MATLAB overwrites the figure window every time you request a new plot • To open a new figure window use the figure function – for example figure(2) 71 Creating Multiple Plots Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 72. • hold on – Freezes the current plot, so that an additional plot can be overlaid • When you use this approach the additional line is drawn in blue – the default drawing color 72 MULTIPLE GRAPHS IN A SAME PLOT The first plot is drawn in blue Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 73. 73 The hold on command freezes the plot The second line is also drawn in blue, on top of the original plot The second line is also drawn in blue, on top of the original plot Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 74. Using hold command Invoking hold on at any point freezes the plot in the graphics window Subsequent plots are added to existing plot Dr. Manish K Rathod, Assistant Professor, MED, Surat 74
  • 75. Dr. Manish K Rathod, Assistant Professor, MED, Surat 75
  • 76. • Multiple lines on a single graph with one command can also be created. 76 MULTIPLE GRAPHS IN A SAME PLOT Plots three graphs in the same plot: yversus x, vversus u, and hversus t.  By default, MATLAB makes the curves in different colors.  Additional curves can be added.  The curves can have a specific style by adding specifiers after each pair, for example: plot(x,y,u,v,t,h) plot(x,y,’-b’,u,v,’—r’,t,h,’g:’) Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 77. 4 2    x Plot of the function, and its first and second derivatives, for , all in the same plot. 10 26 3 3    x x y 4 2    x x = [-2:0.01:4]; y = 3*x.^3-26*x+6; yd = 9*x.^2-26; ydd = 18*x; plot(x,y,'-b',x,yd,'--r',x,ydd,':k') vector x with the domain of the function. Vector y with the function value at each x. 4 2    x Vector yd with values of the first derivative. Vector ydd with values of the second derivative. Create three graphs, y vs. x (solid blue line), yd vs. x (dashed red line), and ydd vs. x (dotted black line) in the same figure. MULTIPLE GRAPHS IN A SAME PLOT Dr. Manish K Rathod, Assistant Professor, MED, Surat 77
  • 78. -2 -1 0 1 2 3 4 -40 -20 0 20 40 60 80 100 120 USING THE plot() COMMAND TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT Dr. Manish K Rathod, Assistant Professor, MED, Surat 78
  • 79. FORMATTING PLOTS A plot can be formatted to have a required appearance. With formatting you can:  Add title to the plot.  Add labels to axes.  Change range of the axes.  Add legend.  Add text blocks.  Add grid. Dr. Manish K Rathod, Assistant Professor, MED, Surat 79
  • 80. FORMATTING PLOTS MATLAB SUPPORTS TWO WAYS TO EDIT THE PLOTS : Using the mouse to select and edit objects interactively (Interactive Plot Editing) Using MATLAB functions at command-line or in an M-file (Using Functions to Edit Graphs) Dr. Manish K Rathod, Assistant Professor, MED, Surat 80
  • 81. FORMATTING COMMANDS title(‘string’) Adds the string as a title at the top of the plot. xlabel(‘string’) Adds the string as a label to the x-axis. ylabel(‘string’) Adds the string as a label to the y-axis. axis([xmin xmax ymin ymax]) Sets the minimum and maximum limits of the x- and y-axes. Dr. Manish K Rathod, Assistant Professor, MED, Surat 81
  • 82. FORMATTING COMMANDS Creates a legend using the strings to label various curves (when several curves are in one plot). The location of the legend is specified by the mouse. legend(‘string1’,’string2’,’string3’) text(x,y,’string’) Places the string (text) on the plot at coordinate x,y relative to the plot axes. gtext(‘string’) Places the string (text) on the plot. When the command executes the figure window pops and the text location is clicked with the mouse. Dr. Manish K Rathod, Assistant Professor, MED, Surat 82
  • 83.  legend (…., pos) : pos = -1 places the legend outside the axes boundary on the right side. pos = 0 places the legend inside the axes boundary, obscuring as few points as possible. pos = 1 places the legend in the upper-right corner of the axes (default). pos = 2 places legend in the upper-left corner of axes. pos = 3 places legend in the lower-left corner of axes. pos = 4 places legend in the lower-right corner of axes.  legend off: deletes the legend from plot FORMATTING COMMANDS Dr. Manish K Rathod, Assistant Professor, MED, Surat 83
  • 84. -1 0 1 3 4 Dr. Manish K Rathod, Assistant Professor, MED, Surat 84
  • 85. EXAMPLE OF A FORMATTED PLOT Below is a script file of the formatted light intensity plot x=[10:0.1:22]; y=95000./x.^2; xd=[10:2:22]; yd=[950 640 460 340 250 180 140]; plot(x,y,'-','LineWidth',1.0) hold on plot(xd,yd,'ro--',‘LineWidth',1.0,'markersize',10) hold off Creating a vector with light intensity from data. Creating a vector with coordinates of data points. Creating vector x for plotting the theoretical curve. Creating vector y for plotting the theoretical curve. Dr. Manish K Rathod, Assistant Professor, MED, Surat 85
  • 86. EXAMPLE OF A FORMATTED PLOT Formatting of the light intensity plot (cont.) xlabel('DISTANCE (cm)') ylabel('INTENSITY (lux)') title('fontname{Arial}Light Intensity as a Function of Distance','FontSize',14) axis([8 24 0 1200]) text(14,700,'Comparison between theory and experiment.','EdgeColor','r','LineWidth',2) legend('Theory','Experiment',0) Creating text. Creating a legend. Title for the plot. Setting limits of the axes. Labels for the axes. The plot that is obtained is shown again in the next slide. Dr. Manish K Rathod, Assistant Professor, MED, Surat 86
  • 87. EXAMPLE OF A FORMATTED PLOT Dr. Manish K Rathod, Assistant Professor, MED, Surat 87
  • 88. 88 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 89. You can use Greek letters in your labels by putting a backslash () before the name of the letter. For example: title(‘alpha beta gamma’) creates the plot title α β γ To create a superscript use curly brackets title(‘x^{2}’) Gives x2 89 IMPROVING LABELS Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 90. FORMATTING A PLOT IN THE FIGURE WINDOW Once a figure window is open, the figure can be formatted interactively. Use Figure, Axes, and Current Object-Properties in the Edit menu Click here to start the plot edit mode. Use the insert menu to Dr. Manish K Rathod, Assistant Professor, MED, Surat 90
  • 91. FORMATTING A PLOT IN THE FIGURE WINDOW Dr. Manish K Rathod, Assistant Professor, MED, Surat 91
  • 92. FORMATTING A PLOT IN THE FIGURE WINDOW Dr. Manish K Rathod, Assistant Professor, MED, Surat 92
  • 93. SAVING A FIGURE Save from File menu saves the a figure To save figure using a graphics format (*.bmp,*.jpg, etc) , select Export from the File menu Dr. Manish K Rathod, Assistant Professor, MED, Surat 93
  • 94. Subplots 94 • The subplot command allows to subdivide the graphing window into a grid of m rows and n columns • subplot(m,n,p) rows columns location 2 rows 2 columns 1 2 3 4 -2 0 2 -2 0 2 -5 0 5 x Peaks y subplot(2,2,1) Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 95. 95 2 rows and 1 column Subplots Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 96. Other Types of 2-D Plots • Polar Plots • Logarithmic Plots • Bar Graphs • Pie Charts • Histograms • X-Y graphs with 2 y axes • Function Plots 96 MATLAB supports a variety of graph types that enable to present information effectively. The type of graph selected depends, to a large extent on the nature of the data Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 97. Logarithmic Plots • A logarithmic scale (base 10) is convenient when – a variable ranges over many orders of magnitude, because the wide range of values can be graphed, without compressing the smaller values. – data varies exponentially. • plot – uses a linear scale on both axes • semilogy – uses a log10 scale on the y axis • semilogx – uses a log10 scale on the x axis • loglog – use a log10 scale on both axes 97 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 98. 98 Logarithmic Plots Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 99. 99 Logarithmic Plots Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 100. • Bar graphs are useful to view results over time, comparing results, and displaying individual contribution to a total amount. • Pie charts show individual contribution to a total amount. • Histograms show the distribution of data values. Bar Graphs and Pie Charts Dr. Manish K Rathod, Assistant Professor, MED, Surat 100
  • 101. Bar Graphs and Pie Charts • MATLAB includes a whole family of bar graphs and pie charts – bar(x) – vertical bar graph – barh(x) – horizontal bar graph – bar3(x) – 3-D vertical bar graph – bar3h(x) – 3-D horizontal bar graph – pie(x) – pie chart – pie3(x) – 3-D pie chart 101 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 102. 102 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 103. 103 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 104. Histograms • A histogram is a plot showing the distribution of a set of values 104 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 105. Stem and stair step plots display discrete data. Stem and Stair 105
  • 106. Polar Plots • Some functions are easier to specify using polar coordinates than by using rectangular coordinates • For example the equation of a circle is – y=sin(x) in polar coordinates 106 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 107. 107 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 108. X-Y Graphs with Two Y Axes • Scaling Depends on the largest value plotted • Its difficult to see how the blue line behaves, because the scale isn’t appropriate 108 Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 109. 109 The plotyy function allows you to use two scales on a single graph X-Y Graphs with Two Y Axes Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 110. Function Plots 110 • Function plots allow you to use a function as input to a plot command, instead of a set of ordered pairs of x-y values • fplot('sin(x)',[-2*pi,2*pi]) function input as a string range of the independent variable – in this case x Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 111. 111 Function Plots Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 112. • Compass, feather, and quiver plots display direction and velocity vectors. • Contour plots show equivalued regions in data. • Interactive plotting enable to select data points to plot with the pointer. Other Plots Dr. Manish K Rathod, Assistant Professor, MED, Surat 112
  • 113. 3 D Graphs Elementary 3-D plots • plot3 - Plot lines and points in 3-D space. • mesh - 3-D mesh surface. • surf - 3-D colored surface. • fill3 - Filled 3-D polygons. plot3(x,y,z) - generates a line in 3-space through the points whose coordinates are the elements of x, y, z. Dr. Manish K Rathod, Assistant Professor, MED, Surat 113
  • 114. • These plots require a set of order triples ( x-y-z values) as input 114 The z-axis is labeled the same way the x and y axes are labeled 3 D Graphs Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 115. 115 MATLAB uses a coordinate system consistent with the right hand rule 3 D Graphs Dr. Manish K Rathod, Assistant Professor, MED, Surat
  • 118. Creating a grid in the x-y plane: X and Y are the matrix of the x and y coordinates of the grid points respectively. x and y are vectors that divides the domain of the x and y respectively. (-1,1) (-1,4) (3,4) (3,1) 3 D Graphs Dr. Manish K Rathod, Assistant Professor, MED, Surat 118
  • 119. For Example, if z=xy2/(x2 + y2) The value of z at each point of the grid is calculated 3 D Graphs Dr. Manish K Rathod, Assistant Professor, MED, Surat 119
  • 121. • Controls the direction from which the plot is viewed. • Done by specifying a direction in terms of azimuth and elevation angles. • View (az,el) or view([az,el]) Angle in the x-y plane measured relative to the negative y axis direction and positive in counter clockwise direction Angle of elevation from x-y plane. 3 D Graphs - View Command Dr. Manish K Rathod, Assistant Professor, MED, Surat 121
  • 122. 3 D Graphs - View Command 122
  • 123. Printing the Figure  using option Print under File menu  using print command  The Export option under File menu to export figure to a variety of standard graphics file format  Using print command Dr. Manish K Rathod, Assistant Professor, MED, Surat 123
  • 124. Dr. Manish K Rathod, Assistant Professor, MED, Surat 124