0% found this document useful (0 votes)
205 views269 pages

3rdyear Lab MATLAB 2019 PDF

MATLAB is a matrix-oriented programming language commonly used for scientific and engineering calculations. It contains built-in functions and toolboxes for tasks like matrix manipulation, data analysis, and visualization. MATLAB can be used interactively in the command window or with script files to perform calculations, analyze data, and develop algorithms. It provides a comprehensive environment for technical computing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
205 views269 pages

3rdyear Lab MATLAB 2019 PDF

MATLAB is a matrix-oriented programming language commonly used for scientific and engineering calculations. It contains built-in functions and toolboxes for tasks like matrix manipulation, data analysis, and visualization. MATLAB can be used interactively in the command window or with script files to perform calculations, analyze data, and develop algorithms. It provides a comprehensive environment for technical computing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 269

MATLAB Introduction

Dr. Litan Kumar Saha


Associate Professor
Department of Applied Mathematics
University of Dhaka
MATLAB Introduction
 MATLAB stands for Matrix Laboratory.
 Matlab had many functions and toolboxes to help
in various applications
 MATLAB is powerful, general-purpose system or
environment for doing mathematics, scientific and
engineering calculations.
 MATLAB is matrix-oriented, so what would take
several statements in C or Fortran can usually be
accomplished in just a few lines using MATLAB's
built-in matrix and vector operations .
MATLAB Introduction

FORTRAN:
real*8 A(10,10), B(10,10), C(10,10)
do i=1,10
do j=1,10
C(i,j) = A(i,j) + B(i,j)
end do
end do

MATLAB:
C=A+B
MATLAB Introduction
 MATLAB is available for MS Windows,
Macintosh personal computer, Unix and other
operating systems.

 MATLAB is a "High-Performance Numeric


Computation and Visualization Software" package.

 MATLAB is an interactive system whose basic


data is a matrix that does not require dimensioning.
MATLAB Introduction
• In Windows
systems
MATLAB is
started by
double-clicking
the mouse on
the appropriate
icon.
File
Edit
View
View
View
Web
Help
What is Matlab
• MATLAB is a numerical computing environment and
programming language.
• Created by The MathWorks, MATLAB allows easy
– matrix manipulation,
– plotting of functions and data,
– implementation of algorithms,
– creation of user interfaces, and
– interfacing with programs in other languages.

• MATLAB is available for Windows, Macintosh and


UNIX systems. It is used by more than one million people
in industry and academia.
13
History MATLAB
Cleve Moler, the chairman of the computer science
department at the University of New Mexico, started
developing MATLAB in the late 1970s.
He designed it to give his students access to LINPACK
and EISPACK without them having to learn Fortran. It
soon spread to other universities and found a strong
audience within the applied mathematics community.
Jack Little, an engineer, was exposed to it during a
visit Moler made to Stanford University in 1983.
Recognizing its commercial potential, he joined with
Moler and Steve Bangert.
History MATLAB
They rewrote MATLAB in C and founded MathWorks
in 1984 to continue its development. These rewritten
libraries were known as JACKPAC. In 2000,
MATLAB was rewritten to use a newer set of libraries
for matrix manipulation, LAPACK.

MATLAB was first adopted by researchers and


practitioners in control engineering, Little's specialty,
but quickly spread to many other domains. It is now
also used in education, in particular the teaching of
linear algebra and numerical analysis, and is popular
amongst scientists involved in image processing.
Advantages
• It allows quick and easy coding in a very high-level
language.
• It lets you work in Matrices easily. Adding two arrays
together needs only one command, instead of a for or while
loop.
• Lots of Predefined functions and toolboxes: fminsearch,
fsolve, normcdf, norminv, etc;
• Lots of users: economists, mathematicians, engineers, …
• High-quality graphics and visualization facilities are
available.
• MATLAB M-files are completely portable across a wide
range of platforms.
• EXTENSIVE documentation (type ‘helpwin’)
Advantages
• Matlab’s functionality can be greatly expanded by the
addition of toolboxes. These are sets of specific functions
that provided more specialized functionality.
Ex: Excel link allows data to be written in a format
recognized by Excel, Statistics Toolbox allows more
specialized statistical manipulation of data (Anova, Basic
Fits, etc)

Disadvantages
• It uses a large amount of memory and on slow computers it
is very hard to use.
• It is very Expensive software.
MATLAB WINDOWS
 Command Window
type commands

 Current Directory
View folders and m-files

 Workspace
View program variables
Double click on a variable
to see it in the Array Editor

 Command History
– view past commands
– save a whole session
using diary
MATLAB
Command
Window
MATLAB WINDOWS
Command Window:
The Command Window is MATLAB’s main window and opens
when MATLAB is started. It is convenient to have the Command
Window as the only visible window, and this can be done by either
closing all the other windows (click on the x at the top right-hand
side of the window you want to close) or by first selecting the
Desktop Layout in the Desktop menu, and then selecting Command
Window Only from the submenu that opens.
Figure Window:
The Figure Window opens automatically when graphics commands
are executed, and contains graphs created by these commands
MATLAB WINDOWS

Editor Window:
The Editor Window is used for writing and editing programs.
This window is opened from the File menu.

Help Window:

The Help Window contains help information. This window can be


opened from the Help menu in the toolbar of any MATLAB
window. The Help Window is interactive and can be used to obtain
information on any feature of MATLAB.
Notes for working in the Command Window
• To type a command the cursor must be placed next to the command prompt( >> ).
• Once a command is typed and the Enter key is pressed, the command is executed.
However, only the last command is executed. Everything executed previously is
unchanged.
• Several commands can be typed in the same line. This is done by typing a comma
between the commands. When the Enter key is pressed the commands are executed in
order from left to right.
• It is not possible to go back to a previous line that is displayed in the Command
Window, make a correction, and then re-execute the command.
• A previously typed command can be recalled to the command prompt with the
uparrow key. When the command is displayed at the command prompt, it can be
modified if needed and then executed. The down-arrow key can be used to move
down the list of previously typed commands.
• If a command is too long to fit in one line, it can be continued to the next line by
typing three periods … (called an ellipsis) and pressing the Enter key. The
continuation of the command is then typed in the new line. The command can
continue line after line up to a total of 4,096 characters.
Using MATLAB as a Calculator
The simplest way to use MATLAB is as a calculator. This is done
in the Command Window by typing a mathematical expression
and pressing the Enter key.
MATLAB calculates the expression and responds by displaying
ans = and the numerical result of the expression in the next line.

>> 27^(1/3)+32^0.2
1/3 is executed first, 27^(1/3) and 32^0.2 are executed
next, and + is executed last.

>> 0.7854-(0.7854)^3/(1*2*3)+0.785^5/(1*2*3*4*5)...
-(0.785)^7/(1*2*3*4*5*6*7)
Type three periods ... (and press Enter) to continue the
expression on the next line.
Using Help in Matlab
Online help is available from the Matlab prompt (>> a double
arrow)
>> helpwin
[a long list of help topics follows]
>> helpwin fminsearch
[a help message on the fminsearch function follows].
>>doc plot
[displays the HTML documentation for the MATLAB function
plot].
>> type norminv
[display brief information of the non-built-in function norminv]
>> lookfor cdf
>> demo
Operators (arithmetic)

For scalars, the left division is the inverse of the right division. The
left division, however, is mostly used for operations with arrays.
Order of Precedence

In an expression that has several operations, higher-precedence


operations are executed before lower-precedence operations. If two or
more operations have the same precedence, the expression is
executed from left to right.
MATLAB Functionality

– Built-in Functionality includes


• Matrix manipulation and linear algebra
• Data analysis
• Graphics and visualisation
• …and hundreds of other functions 
– Add-on toolboxes provide*
• Image processing
• Signal Processing
• Optimization
• Genetic Algorithms
…* but we have to pay for these extras 
DISPLAY FORMATS
MATLAB has several formats for displaying numbers. Details of
these formats can be obtained by typing help format in the
Command Window. The format in which numbers are displayed
does not affect how MATLAB computes and saves numbers.
ELEMENTARY MATH BUILT-IN FUNCTIONS
MATLAB has a very large library of built-in functions. A
function has a name and an argument in parentheses. For
example, the function that calculates the square root of a number
is sqrt(x). Its name is sqrt, and the argument is x. When the
function is used, the argument can be a number, a variable that
has been assigned a numerical value, or a computable expression
that can be made up of numbers and/or variables.
Variables
– Names
• A MATLAB variable is a region of memory containing an array
that is known by a user-specified name
• Can be any string of upper and lower case letters along with
numbers and underscores but it must begin with a letter
• Can be up to 63 characters long.
• No spaces are allowed between characters
• Avoid using the name of a built-in function for a variable (i.e.,
avoid using cos, sin, exp, sqrt, etc.). Once a function name is
used to define a variable, the function cannot be used.
• Names are case sensitive
• Variables are defined with the assignment operator, =.
• It is a dynamically typed language because variables
can be assigned without declaring their type
The following problems can be solved by writing commands in
the Command Window
The following problems can be solved by writing commands in
the Command Window
Vectors
• A vector is a list of numbers
– Use square brackets [] to contain the numbers

• To create a row vector use ‘,’ to separate the content


– To create a column vector use ‘;’ to separate
the content

• A row vector can be converted into a column vector


by using the transpose operator ‘
Matrices
• A MATLAB matrix is a rectangular array of numbers
– Scalars and vectors are regarded as special cases of
matrices
– MATLAB allows you to work with a whole array at a time
• You can create matrices (arrays) of any size using a
combination of the methods for creating vectors
• List the numbers using ‘,’ to separate each column
and then ‘;’ to define a new row
Matrices
• You can also use built in functions to create a matrix
>> A = zeros(2, 4)
creates a matrix called A with 2 rows and 4 columns
containing the value 0
>> A = zeros(5) or >> A = zeros(5, 5)
creates a matrix called A with 5 rows and 5 columns

• You can also use:


>> ones(rows, columns)
>> rand(rows, columns)

Note: MATLAB always refers to the first value as the


number of Rows then the second as the number of
Columns
Clearing Variables
• You can use the command “clear all” to delete all the
variables present in the workspace

• You can also clear specific variables using:


>> clear Variable_Name
Accessing Matrix Elements
• An Element is a single number within a matrix or vector

• To access elements of a matrix type the matrices’ name


followed by round brackets containing a reference to the
row and column number:
>> Variable_Name(Row_Number, Column_Number)
• An element can also be accessed by its memory location
number.

NOTE: In Excel you reference a value by Column, Row. In


MATLAB you reference a value by Row, Column
Accessing Matrix Elements
1st 2nd
Excel MATLAB

2nd 1st

• To access Subject 3’s result for Test 3


– In Excel (Column, Row):
D3
– In MATLAB (Row, Column):
>> results(3, 4)
This entry can also be accessed by the command
>> result (24)

38
Changing Matrix Elements

• The referenced element can also be changed


>> results(3, 4) = 10
or
>> results(24) = 10
Accessing Matrix Rows

• You can also access multiple values from a Matrix


using the : symbol
– To access all columns of a row enter:
>> Variable_Name(RowNumber, :)
Accessing Matrix Columns

• To access all rows of a column


– >> Variable_Name(:, ColumnNumber)
Changing Matrix Rows or Columns

• These reference methods can be used to change the


values of multiple matrix elements

• To change all of the values in a row or column to


zero use
>> results(:, 3) = 0 >> results(:, 5) = results(:, 3) + results(:,
4)
Changing Matrix Rows or Columns

• To overwrite a row or column with new values


>> results(3, :) = [10, 1, 1, 1]
>> results(:, 3) = [1; 1; 1; 1; 1; 1; 1]

NOTE: Unless you are overwriting with a single value the data entered
must be of the same size as the matrix part to be overwritten.
Accessing Multiple Rows, Columns

– To access consecutive Rows or


Columns use : with start and
end points:

– Multiple Rows:
>> Variable_Name(start:end, :)

– Multiple Columns:
>> Variable_Name(:, start:end)

44
Accessing Multiple Rows, Columns
A(:,n) Refers to the elements in all the rows of column n of
the matrix A.
A(n,:) Refers to the elements in all the columns of row n of
the matrix A.
A(:,m:n) Refers to the elements in all the rows between
columns m and n of the
matrix A.
A(m:n,:) Refers to the elements in all the columns between
rows m and n of the
matrix A.
A(m:n,p:q) Refers to the elements in rows m through n and
columns p through q of the matrix A.
Accessing Multiple Rows, Columns

• To access multiple non consecutive Rows or Columns use


a vector of indexes (using square brackets [])

– Multiple Rows:
>>Variable_Name([index1, index2, etc.], :)

– Multiple Columns:
>>Variable_Name(:, [index1, index2, etc.])

B = A([1,3],[1,3,5:7])
Refers reate a matrix B from the 1st and 3rd rows, and 1st,
3rd, and the 5th through 7th columns of A.

46
Changing Multiple Rows, Columns

• The same referencing can be used to change


multiple Rows or Columns

>> results([3,6], :) = 0 >> results(3:6, :) = 0

47
The colon operator

• The colon : is actually an operator, that generates a row


vector
• This row vector may be treated as a set of indices when
accessing a elements of a matrix
• The more general form is
– [start:stepsize:end]
>> [11:2:21]
11 13 15 17 19 21
>>
• Stepsize does not have to be integer (or positive)
>> [22:-2.07:11]
22.00 19.93 17.86 15.79 13.72 11.65
>>
• Also use linspace command.
PROBLEMS
PROBLEMS
PROBLEMS
PROBLEMS
Operators (Element by Element)

.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power
The use of “.” – “Element”
A = [1 2 3; 5 1 4; 3 2 1] Operation
A=
1 2 3
5 1 4
3 2 -1

b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
Inner Product (*)

The inner product is defined by multiplying the corresponding


elements together and adding the results to give a single
number (inner).

Elementwise Product (.*)


X=A\B

Xb=inv(A)*B
Create a sparse 5 x 4 matrix S having only 3 non–zero
values: S1,2 = 10, S3,3 = 11 and S5,4 = 12.
Think about what would be produced by the following sequence of
statements and expressions, and then type them to verify your answers.
i) m = [1:4; 3 11 7 2] ii) m(2,3) iii) m(:,3) iv) m(4) v) size(m)
vi) mat(:,2) = [ ] vii) vec = m(1,:) viii) vec(2) = 5 ix) vec(3) = [ ]
x) vec(5) = 8 xi) vec = [vec 11]
EXAMPLE OF A 2-D PLOT Legend
Plot title
Light Intensity as a Function of Distance
1200
Theory
y axis Experiment

label 1000

Text
Tick-mark
800
INTENSITY (lux)

Comparison between theory and experiment.

600

400
Data symbol

200

0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
The basic 2-D plot command is
plot(x,y)

where x is a vector (one dimensional array),


and y is a vector. Both vectors must have the
same number of elements.

 The plot command creates a single curve with


the x values on the abscissa (horizontal axis) and
the y values on the ordinate vertical axis).

 The curve is made from segments of lines that


connect the points that are defined by the x and y
coordinates of the elements in the two vectors.
2-D Plotting - example
» x = 0:.1:2*pi;
» y = sin(x);
» plot(x,y)
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’)
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’)
Table of line specifiers Options
S Color S Data S Line
Symbol Type

b Blue . Point - Solid


g Green O Circle : Dotted
r Red x x-mark -. Dash-dot
c Cyan + Plus -- Dashed
m Magenta * Star
y Yellow s Square
k Black d Diamond
Examples of using line specifiers options

plot(x, y, ‘k*-’) - Plot y versus x using a solid


black line with an * marker shown for each point

plot(x, y, ‘gd:’) - Plot y versus x using a dotted


green line with a diamond marker shown for each
point

plot(x, y, ‘r+--’) - Plot y versus x using a dashed


red line with a + marker shown for each point
Graph Annotation

TITLE LEGEND

TEXT
or
GTEXT
YLABEL

XLABEL
PLOT OF GIVEN DATA USING LINE
SPECIFIERS IN THE plot() COMMAND

Year 1988 1989 1990 1991 1992 1993 1994

Sales (M) 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.
PLOT OF GIVEN DATA USING LINE
SPECIFIERS IN THE plot() COMMAND

Dashed red line and


asterisk markers.
hold ----Plot the next set of data on the same chart
title(‘text’) --- Adds a title to the top of the graph.
xlabel(‘text’) ---- Adds a label to the x-axis.
ylabel(‘text’) ----Adds a label to the y-axis.
grid on (or grid) ---Turns on the grid lines.
grid off -----Turns off the grid lines.
grid minor ---Turns on the minor grid lines.
Adding additional plots to a figure
• HOLD ON holds the
current plot
• HOLD OFF releases
hold on current plot
• HOLD toggles the hold
state
» x = 0:.1:2*pi;
» y = sin(x);
» plot(x,y,'b')
» grid on
» hold on
» plot(x,exp(-x),'r:*')
Controlling viewing area
• ZOOM ON allows user
to select viewing area
• ZOOM OFF prevents
zooming operations
• ZOOM toggles the
zoom state

• AXIS sets axis range


[xmin xmax ymin ymax]
» axis([0 2*pi 0 1])
Exercise: 2-D Plotting
Create the following graph:

fontsize (14)

sin(10πt)

cos(10πt)

Courier New + Bold


Solution: 2-D Plotting
» t = 0:0.01:0.5;
» plot(t,sin(10*pi*t),'g-*', ...
t,cos(10*pi*t),'k:o')
» title(['\fontsize{14}In-Phase ({\itsolid})', ...
'and Quadrature ({\itdotted}) Signals'])
» xlabel('\fontname{Courier New}\bfTime (\mus)')
» ylabel('{\it''Normalized''} Signals');
» text(0.2, cos(2*pi)+0.1, '\leftarrow----\rightarrow');
» text(0.175, cos(2*pi)+0.2, '^\pi/_2 phase lag');
» axis([0 0.5 -1.5 1.5]);

% NOTE: Could have also used GTEXT or PLOTEDIT:


% =============================================
% gtext('\leftarrow----\rightarrow');
% gtext('^\pi/_2 phase lag');

»plot2d_soln
Subplots
SUBPLOT- display multiple axes in the same figure window
subplot(#rows, #cols, index)
»subplot(2,2,1);
»plot(1:10)

»subplot(2,2,2)
»x = 0:.1:2*pi;
»plot(x,sin(x))

»subplot(2,2,3)
»x = 0:.1:2*pi;
»plot(x,exp(-x),’r’)

»subplot(2,2,4)
»plot(peaks)
»subplotex
Alternative Scales for Axes

LOGLOG SEMILOGY
Both axes log Y
logarithmic linear X

SEMILOGX PLOTYY
log X 2 sets of
linear Y linear axes

»other_axes
CREATING A PLOT OF A FUNCTION

−0.5 x
Consider: y = 3.5 cos(6 x) for − 2 ≤ x ≤ 4
A script file for plotting the function is:
% A script file that creates a plot of
% the function: 3.5^(-0.5x)*cos(6x)
x = [-2:0.01:4]; Creating a vector with spacing of 0.01.

y = 3.5.^(-0.5*x).*cos(6*x);
Calculating a value of y
plot(x,y) for each x.

Once the plot command is executed, the Figure Window


opens with the following plot.
A PLOT OF A FUNCTION
−0.5 x
y = 3.5 cos(6 x) for − 2 ≤ x ≤ 4
CREATING A PLOT OF A FUNCTION

If the vector x is created with large spacing, the graph is


not accurate. Below is the previous plot with spacing of 0.3.

x = [-2:0.3:4];
y = 3.5.^(-0.5*x).*cos(6*x);
plot(x,y)
THE fplot COMMAND

The fplot command can be used to plot a function


with the form: y = f(x)

fplot(‘function’,limits)

 The function is typed in as a string.

 The limits is a vector with the domain of x, and optionally with limits
of the y axis:

[xmin,xmax] or [xmin,xmax,ymin,ymax]

 Line specifiers can be added.


PLOT OF A FUNCTION WITH THE fplot() COMMAND

A plot of: y = x 2 + 4 sin( 2 x) − 1 for − 3 ≤ x ≤ 3

>> fplot('x^2 + 4 * sin(2*x) - 1', [-3 3])


PLOTTING MULTIPLE GRAPHS IN THE SAME PLOT

Plotting two (or more) graphs in one plot:

1. Using the plot command.

2. Using the hold on, hold off commands.


USING THE plot() COMMAND TO PLOT
MULTIPLE GRAPHS IN THE SAME PLOT

plot(x,y,u,v,t,h)

Plots three graphs in the same plot:

y versus x, v versus u, and h versus 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,’-b’,u,v,’—r’,t,h,’g:’)
USING THE plot() COMMAND TO PLOT
MULTIPLE GRAPHS IN THE SAME PLOT

Plot of the function, y = 3 x 3 − 26 x + 10 and its first and second


derivatives, for − 2 ≤ x ≤ 4 , all in the same plot.

x = [-2:0.01:4]; vector x with the domain of the function.


y = 3*x.^3-26*x+6; Vector y with the function value at each x.
−2≤ x ≤ 4
yd = 9*x.^2-26;
Vector yd with values of the first derivative.
ydd = 18*x;
Vector ydd with values of the second derivative.
−2≤ x ≤ 4
plot(x,y,'-b',x,yd,'--r',x,ydd,':k')

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.
USING THE plot() COMMAND TO PLOT
MULTIPLE GRAPHS IN THE SAME PLOT

120

100

80

60

40

20

-20

-40
-2 -1 0 1 2 3 4
USING THE hold on, hold off, COMMANDS
TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT

hold on Holds the current plot and all axis properties so that
subsequent plot commands add to the existing plot.

hold off Returns to the default mode whereby plot commands erase
the previous plots and reset all axis properties before
drawing new plots.

This method is useful when all the information (vectors) used for the
plotting is not available a the same time.
USING THE hold on, hold off, COMMANDS
TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT
Plot of the function, y = 3 x 3 − 26 x + 10 and its first and second
derivatives, for − 2 ≤ x ≤ 4 all in the same plot.

x = [-2:0.01:4];
y = 3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd = 18*x;
plot(x,y,'-b')
First graph is created.
hold on
plot(x,yd,'--r')
plot(x,ydd,':k') Two more graphs are created.
hold off
EXAMPLE OF A FORMATTED 2-D PLOT
Plot title
Light Intensity as a Function of Distance
1200 Legend
Theory
y axis Experiment

label 1000

Text
Tick-mark
800
INTENSITY (lux)

Comparison between theory and experiment.

600

400
Data symbol

200

0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
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.
FORMATTING PLOTS
There are two methods to format a plot:

1. Formatting commands.
In this method commands, that make changes or
additions to the plot, are entered after the plot()
command. This can be done in the Command Window,
or as part of a program in a script file.

2. Formatting the plot interactively in the Figure Window.


In this method the plot is formatted by clicking on the
plot and using the menu to make changes or add
details.
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.
FORMATTING COMMANDS

legend(‘string1’,’string2’,’string3’)
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.

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.
EXAMPLE OF A FORMATTED PLOT

Below is a script file of the formatted light intensity plot

x=[10:0.1:22]; Creating vector x for plotting the theoretical curve.

y=95000./x.^2; Creating vector y for plotting the theoretical curve.

xd=[10:2:22]; Creating a vector with coordinates of data points.


yd=[950 640 460 340 250 180 140]; Creating a vector with light
intensity from data.
plot(x,y,'-','LineWidth',1.0)
hold on
plot(xd,yd,'ro--','linewidth',1.0,'markersize',10)
hold off
EXAMPLE OF A FORMATTED PLOT

Formatting of the light intensity plot (cont.)

xlabel('DISTANCE (cm)') Labels for the axes.


ylabel('INTENSITY (lux)') Title for the plot.
title('\fontname{Arial}Light Intensity as a Function of
Distance','FontSize',14)
axis([8 24 0 1200]) Setting limits of the axes.

text(14,700,'Comparison between theory and


Creating text.
experiment.','EdgeColor','r','LineWidth',2)
legend('Theory','Experiment',0) Creating a legend.

The plot that is obtained is shown again in the next slide.


EXAMPLE OF A FORMATTED PLOT
FORMATTING A PLOT IN THE FIGURE WINDOW

Once a figure window is open, the figure can be formatted interactively.


Use the insert menu to

Use Figure, Click here to start the plot


Axes, and edit mode.
Current Object-
Properties in the
Edit menu
What kind of graphics is possible in Matlab?

0.9

0.8

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0
-3 -2 -1 0 1 2 3

x = -2.9:0.2:2.9;
bar(x,exp(-x.*x));
98
What kind of graphics is possible in Matlab?

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5

Line plot:
x=0:0.05:5;y=sin(x.^2);plot(x,y);
99
What kind of graphics is possible in Matlab?

0.35

0.3

0.25

0.2

0.15

0.1

0.05

-0.05

-0.1

-0.15
0 0.5 1 1.5 2 2.5 3 3.5 4

Stem plot:
x = 0:0.1:4;, y = sin(x.^2).*exp(-x);
stem(x,y)
100
What kind of graphics is possible in Matlab?

10

-5

-10
30
25
20
20
15
10 10
5
0 0

Mesh plot: z=peaks(25); mesh(z);

101
What kind of graphics is possible in Matlab?

10

-5

-10
30
25
20
20
15
10 10
5
0 0

Surface plot:
z=peaks(25);, surf(z);, colormap(jet);

102
What kind of graphics is possible in Matlab?
25

20

15

10

5 10 15 20 25

Contour plot: z=peaks(25); contour(z,16);

103
Conditional Statements + Loops
CONDITIONAL STATEMENTS
Conditional statements enable MATLAB to make decisions.
 The process is similar to the way we (humans) make decisions.
 A condition stated. If the condition is met, one set of actions is taken. If the
condition is not met, either nothing is done, or a second set of actions is taken.
Example:
If I win the Lottery,
•I will quit college, buy a new car, and go fishing.
If I do not win the Lottery,
•I will study harder so that I can get a better job.
If Statement (In real life)

If I have free time,


I will go to visit my friend
. (period)
If Statement (In MATLAB)

condition
If logical expression False
statements True
end Statement
If Statement (Example)

a <= 30
If a <= 30 False
total = 2*a True

end total = 2*a


If-else Statement (In real life)

If I have free time,


I will go to visit my friend
else,
I will send an email to my friend
. (period)
If-else Statement (In MATLAB)

If logical expression condition


statement group 1 True False
else
statement group 2 Statement1 Statement2
end
If-else Statement (Example)

a <= 30
If a <= 30
True False
total = 2*a
else total = 2*a total = a+10
total = a + 10
end
Nested Logic - I (In real life)

If I have free time,


I will go to visit my friend
If my friend is not there
I will leave a message
. (period)
Nested Logic – I (In MATLAB)

False
condition1
If logical expression 1
True
statement group 1
Statement1
If logical expression 2
Statement group 2 False
condition2
end
end True
Statement2
Nested Logic – I (Example)

False
a <= 30
If a <= 30
c = a + 10 True

If c <= 12 c = a + 10

c=0 False
end c <= 12
end True
c=0
Nested Logic – II (In real life)

If I have free time,


I will go to visit my friend
elseif I can access computer
I will send an email to my friend
else
I will leave a note to my friend
. (period)
Nested Logic – II (In MATLAB)

condition1 False
True
If logical expression 1
statement group 1 condition2
elseif logical expression 2 Statement1 True False
statement group 2
else Statement2 Statement3
statement group 3
end
Nested Logic – II (Example)

a <= 30 False
True
If a <= 30
c=a*2 c >= 20
elseif c >= 20 c=a*2 True False
d=c
else d=c d=0
d=0
end
USING THE if–elseif-else-end STATEMENT
Write program that calculates tip based on amount of bill, using the
following rules

If
bill < $10 False
• Bill less than $10
True
• Tip is $1.80
ElseIf False
• Bill between $10 and $60
$10 < bill < $60
• Tip is %18 Else
• Bill above $60 tip = $1.80 True

• Tip is %20 tip = tip =


bill * 0.18 bill * 0.20

End
USING THE if–elseif-else-end STATEMENT

% A script file that calculates the tip in a restaurant


bill = input('Enter the amount of the bill (in dollars): ');
if (bill <= 10)
tip = 1.8;
elseif (bill > 10) & (bill <= 60)
tip = bill*0.18;
else
tip = bill*0.2;
end
disp('The tip is (in dollars):')
disp(tip)
if–elseif-else-end example
%DEMO
%Header
function output = DEMO(input)

%put help info here!

%Do stuff
if input > 0
fprintf(‘Greater than 0’)
elseif input < 0
fprintf(‘Less than 0’)
else
fprintf(‘Equals Zero’)
end

%Set return value if needed


outvar = 1;

120
Write an if construct that will assign the grades as
previously described using (a) multiple elseif clauses
and (b) nested if constructs.

% One possible structure using elseif clauses is


if grade > 95.0
disp('The grade is A.');
elseif grade > 86.0
disp('The grade is B.');
elseif grade > 76.0
disp('The grade is C.');
elseif grade > 66.0
disp('The grade is D.');
else
disp('The grade is F.');
end
Write an if construct that will assign the grades as
previously described using (a) multiple elseif clauses
and (b) nested if constructs.

% One possible structure using nested if clauses is


if grade > 95.0
disp('The grade is A.');
else
if grade > 86.0
disp('The grade is B.');
else
if grade > 76.0
disp('The grade is C.');
else
if grade > 66.0
disp('The grade is D.');
else
disp('The grade is F.');
end
end
end
end
Loops
 Repeating a calculation for a number of times
 Each repetition of the loop is a pass
 . MATLAB has two kinds of loops.
 for loop (executes a group of statements a
predetermined number of times)

 w hile loop (executes a group of statements


repeatedly as long as the controlling expression is
true)
123
for loops
Set loop variable = m

for index = start:inc:end


True
Variable > n
statements
False
end Statements

Increment variable by s
for loops (Example)
a=1

for a = 1:2:10
True
total = total + a a > 10
end
False
total = total +a

a=a+2
for loops
for loop variable = m:s:n
statements
end

Note:

for a = 10:-2:0 for a = 1:100 for a = 10:2:5


c=a*2 c=a*2 c=a*2
end end end

for a = 2:2 for a = 2:1.5:20


c=a*2 c=a*2
end end

126
w hile loops
initialize k

While expression while done


k<10
statements
computations
end
change k

 Will do computational loop ONLY if while condition is met


 Be careful to initialize while variable
 Can loop forever if while variable is not updated within loop!!!
For and While Loops
for index = array while expression
statement1; statement1;
statement2; statement2;
end end
 In every iteration of  If the expression is
the loop the index true -> run another
equals to one column iteration
of the array.  Pitfall – endless loop

128
Nested loops
for index1 = array1 for index1 = array1
statement1;
statement1; statement2;
statement2; while expression
for index2 = array2 statement3;

statement3; statement4;
if expression1
statement4; statement5;
end end
end end
end

Indentation! No limitations of nesting


order and # levels
129
Break, Continue
and return affect the flow

Only inside loops!


 break – immediately breaks the
loop
 Breaks only one loop
 continue – jump to the end
statement.
 Does not break the loop

Anywhere
 return – returns control to the
command line (or to the calling
function).

130
Problem
 The following were the daily maximum temperatures (in F) in
Washington, DC, during the month of April 2002: 58 73 73 53
50 48 56 73 73 66 69 63 74 82 84 91 93 89 91 80 59 69 56 64 63
66 64 74 63 69 (data from the U.S. National Oceanic and
Atmospheric Administration). Use relational and logical
operations to determine the following:
 (a) The number of days the temperature was above 75 .
 (b) The number of days the temperature was between 65 and 80 .
 (c) The days of the month when the temperature was between 50
and 60 .

131
Problem
 A worker is paid according to his hourly wage up to 40 hours,
and 50% more for overtime. Write a program in a script file that
calculates the pay to a worker. The program asks the user to
enter the number of hours and the hourly wage. The program
then displays the pay.

132
Problem
 A vector is given by
V = [5, 17, –3, 8, 0, –7, 12, 15, 20, –6, 6, 4, –7, 16].
Write a program as a script file that doubles the elements
that are positive and are divisible by 3 or 5, and, raises to
the power of 3 the elements that are negative but greater
than –5.

133
Modify vector elements
• A vector is given by V = [5, 17, –3, 8, 0, –7, 12, 15,
20, –6, 6, 4, –7, 16]. Write a program as a script file
that doubles the elements that are positive and are
divisible by 3 or 5, and, raises to the power of 3 the
elements that are negative but greater than –5.
RELATIONAL AND LOGICAL
OPERATORS
• A relational operator compares two numbers by
determining whether a comparison statement (e.g.,
5 < 8) is true or false.

• If the statement is true, it is assigned a value of 1.


If the statement is false, it is assigned a value of 0.

• A logical operator examines true/false statements


and produces a result that is true (1) or false (0)
according to the specific operator.
Relational operators in MATLAB
RELATIONAL OPERATORS
RELATIONAL OPERATORS
RELATIONAL OPERATORS
Logical operators in MATLAB
Logical operators in MATLAB
Arithmetic, relational, and logical operators
Arithmetic, relational, and logical operators
The following were the daily maximum temperatures
(in F) in Washington, DC, during the month of April
2002: 58 73 73 53 50 48 56 73 73 66 69 63 74 82 84
91 93 89 91 80 59 69 56 64 63 66 64 74 63 69 (data
from the U.S. National Oceanic and Atmospheric
Administration). Use relational and logical operations
to determine the following:
(a) The number of days the temperature was above
75 .
(b) The number of days the temperature was between
65 and 80 .
(c) The days of the month when the temperature was
between 50 and 60 .
Solution
Reading and storing file data
• There are many functions which are used to get data from
the files.

’load’ function: To load variables/data in workspace from


the disk file Different syntax are

load %load matlab.mat (default) file

Load(‘filename’) %load complete file whose name is given

Load(‘filename’, ’x’, ’y’, ’z’) %load only variables x, y, z of given file


Load filename x, y, z %same as above
Reading and storing file data

Note:-
1. No extension with file name means .mat file
2. If file name has extension other than (.mat) it will be treated
as ASCII data file
3. Load function is use only if data file contains numeric data
Reading and storing file data
>>edit abc.txt
Write following and save it
1 3 4 5 7
6 7 8 0 9
>>load abc.txt %it will load this file in workspace with a
% variable name abc, to check it write abc
>>abc
1 3 4 5 7
6 7 8 0 9
If we want to change the variable name write following
command
>>test=load (‘abc.txt’) %now data ‘abc.txt’ will store in variable ‘test’
Reading and storing file data
2.’save’ function: To save variables/data from workspace
to disk file
Different syntax are
save %save all workspace data in matlab.mat file

save(‘filename’) %save complete workspace


data in specified file name
save(‘filename’, ’x’, ’y’, ’z’) %save only variables x, y, z in a file
save filename x, y, z %same as above
Reading and storing file data
Note:-
1. No extension with file name means .mat file
2. If file name has extension other than (.mat) it will be
treated as ASCII data file
3. To save variables to a directory other than current
directory, full pathname of the file has to be specified.
Display command
• disp(name of a variable) or
• disp(‘text as string’)
• Every time the disp command is executed, the
display it generates appears in a new line.
• Only one variable can be displayed in a disp
command. If elements of two variables need to be
displayed together, a new variable (that contains
the elements to be displayed) must first be defined
and then displayed.
Display command
Display command
• In many situations it is nice to display output
numbers) in a table. This can be done by first
defining a variable that is an array with the
numbers and then using the disp command to
display the array. Headings to the columns can
also be created with the disp command. Since in
the disp command the user cannot control the
format (the width of the columns and the distance
between the columns) of the display of the array,
the position of the headings has to be aligned with
the columns by adding spaces.
Display command
• Formatted Output
– fprintf('format string', var, ...)
• %f fixed point
• %e exponential notation
• %w.pf w=width, p=precision
• \n linefeed (endl)
• \t tab
– Example
• fprintf('The answer is %5.2f volts.\n', v)

The answer is 5.25 volts.


fprintf command
To display text, the fprintf command has the form:

fprintf(‘text typed in as a string’)

fprintf('The problem, as entered, has


no solution. Please check the input
data.')

The following is displayed in the Command Window:

The problem, as entered, has no solution. Please check the input data.
fprintf command
With the fprintf command it is possible to start a new line in
the middle of the string. This is done by inserting \n before the
character that will start the new line.

fprintf('The problem, as entered, has no solution.\n Please check the


input data.')

The problem, as entered, has no solution.


Please check the input data.
fprintf command
The fprintf command can be used to display output
(text and data) on the screen or to save it to a file.
With this command (unlike with the disp command)
the output can be formatted. For example, text and
numerical values of variables can be intermixed and
displayed in the same line. In addition, the format of
the numbers can be controlled.

fprintf(‘text typed in as a string’)


fprintf('The problem, as entered, has
no solution. Please check the input
data.')
fprintf command
Using the fprintf command to display a mix of
text and numerical data:
fprintf command
fprint function
>> a=2;b=3;c=5;
>> fprintf('a = %d , b = %d, c = %d', a, b, c);
a = 2 , b = 3, c = 5

>> fprintf('a=%d , b=%d', a, b);fprintf('a+b=%d ', a+b);


a=2 , b=3 a+b=5

>> fprintf('a=%d , b=%d \n', a, b);fprintf('a+b=%d ',


a+b);
a=2 , b=3
a+b=5
Low-level input-output functions
‘fprintf ‘ function: Syntax is
fprintf(fid, format, data)

Exp: Create a file having following code and rut


it.

x = 0:.1:1; y = [x; exp(x)];


fid = fopen('exp.txt','w');
fprintf(fid,'%6.2f %12.8f\n', y);
fclose(fid);
Now open the file ‘exp.txt’ and see the data
Low-level input-output functions

Note: 1. Here %6.2f .


it always starts with % sign
6 = total width of field
2 = no of digits after decimal
f = fixed point
2. fprintf(‘%6.2f %12.8f\n’, y ) will print on
monitor,
here fid =0 i.e monitor
Low-level input-output functions

Note:
1. '%6.2f %12.8f\n‘ here note the space b/w
to formats
2. \n means new line
3. ‘fprintf ‘ displays only real portion of complex
value
Low-level input-output functions

In general ‘format’ may be written as


%a.be
Or %+a.be % + = always print with sign
character (+ or -)
Or %-a.be % - = left justified
Or %0a.be % pad zeros in starting
Here
a = field width
b = digits after decimal point
e = conversion character (%c for char, %s for
string, %d for int, %e for exponential, %f for
fixed point etc)
3d plot in MATLAB Basic Graphics - 168

Subplots
Subplot(m,n,p) ≡ creates mxn subplots in the current figure (array of
subplots), m rows and n columns. p is the current subplot.

»subplot(2,2,1);
»plot(1:10)

»subplot(2,2,2)
»x = 0:.1:2*pi;
»plot(x,sin(x))

»subplot(2,2,3)
»x = 0:.1:2*pi;
»plot(x,exp(-x),’r’)

»subplot(2,2,4)
»plot(peaks)
»subplotex
3d plot in MATLAB Basic Graphics - 169

Alternative Scales for Axes

LOGLOG SEMILOGY
Both axes log Y
logarithmic linear X

SEMILOGX PLOTYY
log X 2 sets of
linear Y linear axes

»other_axes
3d plot in MATLAB Basic Graphics - 170

3-D Line Plotting


plot3(xdata, ydata, zdata, 'clm', ...)

>> theta=0:0.1:10.*pi;
>> plot3(sin(theta),cos(theta),theta)
>> grid on
theta=0:0.1:10.*pi;
>> plot3(sin(theta),cos(theta),theta)
>> grid on

>> theta=0:0.1:10.*pi;
>> plot3(sin(theta),cos(theta),theta)
>> grid on
theta=0:0.1:10.*pi;
»plot_3d
>> plot3(sin(theta),cos(theta),theta)
>>Ref:
gridColor,
on Linestyle, Marker options
3d plot in MATLAB Basic Graphics - 171

3-D Line Plotting


plot3(xdata, ydata, zdata, 'clm', ...)

>> turns=40.*pi;
>> theta=linspace(0,turns,4000); 1
Here is a piece of text!
>> x=cos(theta).*(turns-theta)./turns;
>> y=sin(theta).*(turns-theta)./turns;
0.5
>> z=theta./turns;
>> plot3(x,y,z)
0
>> grid on 1
>> turns=40.*pi;
>> >> text(0.5,0.5,0.75,'Here
theta=linspace(0,turns,4000); is a piece of 1
0
text!');
>> x=cos(theta).*(turns-theta)./turns;
>> y=sin(theta).*(turns-theta)./turns;
0
>> z=theta./turns; -1 -1
>> plot3(x,y,z)
>>»plot_3d
grid on
>>Ref: Color, Linestyle, Marker
text(0.5,0.5,0.75,'Here is a options
piece of
text!');
3d plot in MATLAB Basic Graphics - 172

3-D Surface Plotting

»surf_3d
3d plot in MATLAB Basic Graphics - 173

Exercise: 3-D Plotting


• Data from a water jet experiment suggests the
following non-linear model for the 2-D stress in
the cantilever beam’s horizontal plane.

x
σ = αe-βx[sin(θx)*cos(φy)]

where: σ = localized planar stress [MPa]


x = distance from end of beam [10-1m]
y = distance from centerline of beam [10-1m]
• For the particular setup used:
(x = {0 to 6}, y = {-3 to 3}, α = θ = φ = 1, β = -0.2)
• Plot the resulting stress distribution
3d plot in MATLAB Basic Graphics - 174

Solution: 3-D Plotting


» B = -0.2;
» x = 0:0.1:2*pi;
» y = -pi/2:0.1:pi/2;
» [x,y] = meshgrid(x,y);
» z = exp(B*x).*sin(x).*cos(y);
» surf(x,y,z)

»plot3d_soln
3d plot in MATLAB Basic Graphics - 175

Specialized Plotting Routines

»spec_plots
3d plot in MATLAB Basic Graphics - 176

3D Surface Plots
• Plot functions of the form: z=f(x, y)
• for each (x,y), we can compute a value for z
• this defines a surface in 3D space
• If we can define (x,y) at regular intervals, Matlab
provides powerful ways to plot the resulting function
as a mesh or surface in 3D.

• The (x,y) values stored in arrays will define a grid of


mesh points through which the surface will be
created.

• There are tools in Matlab to handle the situation in


which (x,y) are not defined in a grid, but we won't
consider them in this course.
176
3d plot in MATLAB Basic Graphics - 177

x =-3 -2 -1 0 1 2 3
y =-3 -2 -1 0 1 2 3
z=f(x,y)

This works: corresponding elements


10 of xx & yy contain the x and y
5 coordinates to be used for f(x,y) at
that point
z-axis

-5
xx =-3 -2 -1 0 1 2 3
-3 -2 -1 0 1 2 3
-3 -2 -1 0 1 2 3
-10
-3 -2 -1 0 1 2 3
2 -3 -2 -1 0 1 2 3
2 -3 -2 -1 0 1 2 3
0
0 -3 -2 -1 0 1 2 3
-2 -2
y-axis x-axis yy =-3 -3 -3 -3 -3 -3 -3
-2 -2 -2 -2 -2 -2 -2
NOTE: -1 -1 -1 -1 -1 -1 -1
0 0 0 0 0 0 0
xx varies along ROWS while yy varies
1 1 1 1 1 1 1
along COLUMNS 2 2 2 2 2 2 2
3 3 3 3 3 3 3
z=f(xx,yy) 177
3d plot in MATLAB meshgrid() Basic Graphics - 178

• Matlab provides a function to compute these arrays:


>> x=-3.5:3.5; NOTE #1:
>> y=-2.5:2.5; xx varies along ROWS while yy varies
>> [xx,yy]=meshgrid(x,y) along COLUMNS
xx =
-3.5 -2.5 -1.5 -0.5 0.5 1.5 2.5 3.5 NOTE #2:
-3.5 -2.5 -1.5 -0.5 0.5 1.5 2.5 3.5
For any (i, j), the value in xx
-3.5 -2.5 -1.5 -0.5 0.5 1.5 2.5 3.5
is the x coordinate, while the
-3.5 -2.5 -1.5 -0.5 0.5 1.5 2.5 3.5
value in yy is the y
-3.5 -2.5 -1.5 -0.5 0.5 1.5 2.5 3.5
coordinate:
-3.5 -2.5 -1.5 -0.5 0.5 1.5 2.5 3.5
yy =
xx(3,1) = -3.5
-2.5 -2.5 -2.5 -2.5 -2.5 -2.5 -2.5 -2.5
yy(3,1) = -0.5
-1.5 -1.5 -1.5 -1.5 -1.5 -1.5 -1.5 -1.5
So (x,y) = (-3.5, -0.5)
-0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 NOTE #3:
Matlab calls these arrays "plaids"
0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5
1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 NOTE #4:
2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 We can use array math to
efficiently compute the z
178
values when z=f(x,y)
3d plot in MATLAB meshgrid() Basic Graphics - 179

• In this case we will plot z = (x2 + y2) over the range


-3 ≤ x ≤ 3 and -3 ≤ y ≤ 3
>> x=-3:3;
>> y=-3:3;
>> [xx,yy]=meshgrid(x,y)
xx = 20
3 -2 -1 0 1 2 3
-3 -2 -1 0 1 2 3 15
-3 -2 -1 0 1 2 3
-3 -2 -1 0 1 2 3
10
-3 -2 -1 0 1 2 3
-3 -2 -1 0 1 2 3
-3 -2 -1 0 1 2 3 5
yy =
-3 -3 -3 -3 -3 -3 -3
0
-2 -2 -2 -2 -2 -2 -2
4
-1 -1 -1 -1 -1 -1 -1
2 4
0 0 0 0 0 0 0
0 2
1 1 1 1 1 1 1 0
2 2 2 2 2 2 2 -2 -2
3 3 3 3 3 3 3 -4 -4
>> zz=xx.^2 + yy.^2;
>> mesh(xx,yy,zz) NOTE:
Matlab's array instructions make this a deceptively
Fall 2006 simple
AE6382calculation for all values at once…
Design Computing 179
3d plot in MATLAB Basic Graphics - 180

Key Concepts for z=f(x,y) Plots


• 3D plotting introduces several key
concepts:
• Meshes versus Surfaces
• Hidden line removal
• Pedestals and contours
• Color maps and pseudo-coloring
• The following figures demonstrate these
concepts, but you are encouraged to check this
out in your textbook (using Matlab’s graphic
brings out the real fun in using this powerful
software!).
3d plot in MATLAB Hidden Line Removal Basic Graphics - 181

• This uses an interesting built-in function sphere( )


• Hidden lines:
• ON: shows white inside mesh
• OFF: shows transparent mesh

[X,Y,Z] = sphere(12); Fig 26.5a: Opaque Fig 26.5b: Transparent

subplot(1,2,1);
mesh(X,Y,Z), title('Figure 26.5a: Opaque');
hidden on;
axis square off;
subplot(1,2,2);
mesh(X,Y,Z),title('Figure 26.5b:
Transparent');
hidden off;
axis square off;
3d plot in MATLAB mesh( ) Basic Graphics - 182

• We'll use peaks( ) to create a z=f(x,y) function that is interesting


and shows off the 3D plotting
• Note: you should check help peaks and help mesh and also
the textbook for further details on these functions

>> [x,y,z]=peaks(30);
>> mesh(x,y,z)
>> axis tight 5

>> xlabel('x-axis')
z-axis

0
>> ylabel('y-axis')
>> zlabel('z-axis')
-5

2
Suggestion: 2
0
0
Try using hidden off and -2 -2
hidden on to see what happens. y-axis x-axis
3d plot in MATLAB Basic Graphics - 183

• meshc( ) adds a contour plot directly below the


mesh
• helps visualize the contours
• can locate the peaks and dips
>> [x,y,z]=peaks(30);
>> meshc(x,y,z)
>> axis tight 5

>> xlabel('x-axis')
z-axis 0
>> ylabel('y-axis')
-5
>> zlabel('z-axis')
-10

Hint:: 2
2
0
If you just finished the previous 0
-2 -2
example, you need only type in y-axis x-axis
the new meshc( ) command.
meshz
3d plot in MATLAB Basic Graphics - 184

• This special variation allows you to emphasize the


zero plane in the mesh plot

>> [x,y,z]=peaks(30);
>> meshz(x,y,z) 5
>> axis tight
>> xlabel('x-axis') 0
>> ylabel('y-axis')
>> zlabel('z-axis') -5

2
2
0
0
-2 -2
3d plot in MATLAB waterfall Basic Graphics - 185

• This is another variation on the mesh plot and can


also be useful in some special cases

>> [x,y,z]=peaks(30);
>> waterfall(x,y,z)
>> axis tight 5
>> xlabel('x-axis')
z-axis

>> ylabel('y-axis') 0
>> zlabel('z-axis')
-5

2
2
0
0
-2 -2
y-axis x-axis
3d plot in MATLAB Basic Graphics - 186

Let's Explore the surf( ) Function


• So far we have only been able to plot meshes to
represent the surface
• can hide hidden lines to clarify the surface shape
• still appears as a wireframe-like shape
• Matlab provides a function that will fill in the
mesh with facets (surfaces with 3 or 4 corners
but not necessarily plane surfaces)
• we'll see that these can produce very realistic
appearing surfaces in 3D
• can control appearance of mesh
• can change color mapping to reveal other
information
• can add lighting
3d plot in MATLAB Basic Graphics - 187

Exploring surf Plots (shading faceted)


• The basic function uses the default shading
faceted and this shows the mesh:

>> [x,y,z]=peaks(30);
5
>> surf(x,y,z) z-axis
>> axis tight 0
>> xlabel('x-axis')
>> ylabel('y-axis') -5

>> zlabel('z-axis') 2
2
0
0
-2 -2
y-axis x-axis
3d plot in MATLAB Basic Graphics - 188

Exploring surf Plots (shading flat)


• shading flat will eliminate the mesh and leave the
facets colored with a constant color value

>> [x,y,z]=peaks(30);
>> surf(x,y,z)
>> shading flat 5
>> axis tight
z-axis

>> xlabel('x-axis') 0
>> ylabel('y-axis')
>> zlabel('z-axis') -5

2
2
0
0
-2 -2
y-axis x-axis
3d plot in MATLAB Basic Graphics - 189

Example: Working with Defaults


Set the Default Surface EdgeColor to Blue & create new surface.
» set(0, 'DefaultSurfaceEdgeColor', 'b')
» h=surf(peaks(15));

Set the EdgeColor to Green


» set(h, 'EdgeColor', 'g')

Reset back to Default Value


» set(h, 'EdgeColor', 'default')

specifies Default value

Reset back to Factory Value


» set(h, 'EdgeColor', 'factory')

specifies Factory value


»defaults
3d plot in MATLAB Basic Graphics - 190

Working with Defaults - removing


Return Default Property Value to Factory Setting:
» set(gcf, 'DefaultSurfaceEdgeColor', 'factory')
OR
» set(gcf, 'DefaultSurfaceEdgeColor', 'remove')

Create a new surface:


» h = surf(peaks(15));

»defaults
Polynomials and Curve Fitting
Polynomials are functions that have the form:
m −1
y= p ( x)= am x + am −1 x
m
+ ..... + a1 x + a0
The coefficients am, am-1, …a0 are real numbers, and n,
which is a nonnegative integer, is the degree, or order,
of the polynomial.
In MATLAB, polynomials are represented by a row
vector in which the elements are the coefficients am,
am-1, …a0. The first element is the coefficient of the x
with the highest power. The vector has to include all
the coefficients, including the ones that are equal to 0.

191
Polynomials and Curve Fitting

192
Polynomials and Curve Fitting
Polynomials can be used to fit data points in two ways. In one the polynomial
passes through all the data points, and in the other the polynomial does not
necessarily pass through any of the points, but overall gives a good approximation
of the data.
Curve fitting with polynomials is done in MATLAB with the polyfit
function, which uses the least squares method. The basic form of the polyfit
function is: p = polyfit(x, y, n)

vector of the vector with the vertical degree of the


coefficients of horizontal coordinates of the polynomial
the polynomial coordinates of the data points
that fits the data. data points (dependent
(independent variable).
variable).

193
Polynomials and Curve Fitting
The value of a polynomial at a point x can be calculated with the function polyval
which has the form: polyval (p, x)

p is a vector with the x is a number, or a variable that


coefficients has an assigned value, or a
of the polynomial. computable expression.

y = polyval(a, x)
compute the value of polynomial at value x
y = a(1) xn + a(2) xn-1 + … + a(n) x + a(n+1)
x can be a vector
194
polyfit, polyval
• p = polyfit( x, y, n);
– returns n'th order polynomial that's the closest fit
to x-y data (x and y are vectors, n a scalar)

• yp = polyval( p, x )
– returns the vector yp = the values of polynomial p
at each value in x
Linear Regression
•Assume n points, with each point having values
of both an independent variable x and a
dependent variable y.

The values of x are x1 , x2 , x3 ,...., xn .


The values of y are y1 , y2 , y3 ,...., yn .
A best-fitting straight line equation
will have the form
=
y a1 x + a0
196
Preliminary Computations
n
1
=
x sample mean of the x values ∑
n k =0
xk

1 n
=
y sample mean of the y values ∑
n k =0
yk

1 n 2
x2 =
sample mean-square of the x values ∑
n k =1
xk

1 n
xy =
sample mean of the product xy ∑
n k =1
xk yk

197
Best-Fitting Straight Line
a1 =
( xy ) − ( x )( y )
(x )−(x)
2 2

=
( x ) ( y ) − ( x )( xy )
2

(x )−(x)
a0 2
2

Alternately, a0= y − a1 x
=
y a1 x + a0
198
Find best fitting straight line equation
for the data shown below.
x 0 1 2 3 4 5 6 7 8 9
y 4.00 6.10 8.30 9.90 12.40 14.30 15.70 17.40 19.80 22.30

1 10 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 45
=
x ∑
10 k =1
x=
k
10
= = 4.50
10

1 10 4 + 6.1 + 8.3 + 9.9 + 12.4 + 14.3 + 15.7 + 17.4 + 19.8 + 22.3


=y = ∑ k
10 k =1
y
10
130.2
= = 13.02
10

199
1 10 2
x = ∑ xk
2

10 k =1
(0) 2 + (1) 2 + (2) 2 + (3) 2 + (4) 2 + (5) 2 + (6) 2 + (7) 2 + (8) 2 + (9) 2
=
10
285
= = 28.50
10
1 10
xy = ∑ xk yk
10 k =1
0 + 6.1 + 16.6 + 29.7 + 49.6 + 71.5 + 94.2 + 121.8 + 158.4 + 200.7
=
10
748.6
= = 74.86
10
200
(=
xy ) − ( x )( y ) 74.86 − (4.50)(13.02)
(x )−(x)
a1
2 2
28.50 − (4.50) 2

16.27
= =1.9721
8.250
a0 =y − a1 x =13.02 − 1.972 × 4.50 =4.1455

=y 1.9721x + 4.1455

201
•>> x = 0:9;
•>> yapp = 1.9721*x + 4.1455;
•>> y = [the 10 values of y];
•>> plot(x, yapp, x, y, 'o')

•The best-fit plot and the actual points are


shown on the next slide.

202
203
MATLAB General Polynomial Fit
The values of x are x1 , x2 , x3 ,...., xn .
The values of y are y1 , y2 , y3 ,...., yn .
The polynomial fit is to be of the form
y= p ( x)= am x m + am −1 x m −1 + ..... + a1 x + a0
•>> x = [x1 x2 x3.......xn];
•>> y = [y1 y2 y3......yn];
•>> p = polyfit(x, y, m)
•>> yapp = polyval(p, x)
•>> plot(x, yapp, x, y, 'o')

204
•>> x = 0:9;
•>> y = [the 10 values of y];
•>> p = polyfit(x, y, 1)
•p =
• 1.9721 4.1455

•These are the same values obtained manually in


previous Example.

205
For data of previous two examples,
obtain a 2nd degree fit.
•Assume that the vectors x and y are still in
memory.
•>> p = polyfit(x, y, 2)
•p =
• 0.0011 1.9619 4.1591
•>> yapp2 = polyval(p, x);
•>> plot(x, yapp2, x, y, 'o')

•The results are shown on the next slide.


206
207
Determine several polynomial fits for
the function below.
y sin π t for −1 ≤ t ≤ 1
•>> t = -1:0.05:1;
•>> y = sin(pi*t);
•>> plot(t, y)

•A plot of the function is shown on the next


slide.
208
209
• (a) m = 1

• >> p1 = polyfit(t, y, 1)
• p1 =
• 0.8854 0.0000
• >> yapp1 = polyval(p1, t);
• >> plot(t, yapp1, t, y, 'o')

• The results are shown on the next slide.


210
211
•(b) m = 2
•>> p2 = polyfit(t, y, 2)
•p2 =
• 0.0000 0.8854 -0.0000

•The polynomial is the same as for m = 1. This is due


to the fact that the sine function is an odd function
and the coefficients of the terms with even degrees
are zero.

212
•(c) m = 3
•>> p3 = polyfit(t, y, 3)
•p3 =
• -2.8139 -0.0000 2.6568 0.0000
•>> yapp3 = polyval(p3, t);
•>> plot(t, yapp3, t, y, 'o')

•The results are shown on the next slide. A fit for m


= 4 would be the same as for m = 3.

213
214
• m=5
• >> p5 = polyfit(t, y, 5)
• p5 =
• 1.6982 0.0000 -4.7880 -0.0000 3.0990
0.0000
• >> yapp5 = polyval(p5, t);
• >> plot(t, yapp5, t, y, 'o')

• The results are shown on the next slide.

215
216
For data below, obtain a 2nd degree fit
for the temperature T as a function of
the distance x.
x(ft) 0 1 2 3 4 5
T (deg F) 71 76 86 100 118 140

•>> x = 0:5;
•>> T = [71 76 86 100 118 140];
•>> p = polyfit(x,T,2)
•p =
• 2.0893 3.4107 70.8214
217
The equation is
T = 2.0893 x + 3.4107 x + 70.8214
2

•>> x1 = 0:0.1:5;
•>> T1 = polyval(p, x1);
•>> plot(x1, T1, x, T, 'o')

•The results are shown on the next slide.


218
219
• The following data are related to the life expectances of citizens
of two
• European regions.
• 1975 1980 1985 1990
• WE: 72.8 74.2 75.2 76.4
• EE: 70.2 70.2 70.3 71.2
• Interpolate each set of data with a polynomial of degree 3 and
• estimate the life expectances in 1970, 1983, and 1988.
• Plot each fit along with the data and label your plots.

220
Fit for Problem 5-30a)

• best described by a linear function


x=[25 30 35 40 45];
y=[5 260 480 745 1100];
pfit=polyfit(x,y,1); % derive fit
xmodel=25:45; % construct fit curve
ymodel=polyval(p,xmod); % y values for model
plot(x,y,'*'); hold on;
plot(xmodel, ymodel), xlabel('x'), ylabel('y')
text(35,200,'p=53.5 -1354.5')
Plot for Ex5-30a)
Polynomials and Curve Fitting
yi = interp1(x, y, xi, ‘method’)
• ‘nearest’ returns the value of the data point that is
nearest to the
• interpolated point.
• ‘linear’ uses linear spline interpolation.
• ‘spline’ uses cubic spline interpolation.
• ‘pchip’ uses piecewise cubic Hermite interpolation,
also called ‘cubic’

223
Symbolic Mathematics
Dr. Litan Kumar Saha
Assistant Professor
Department of Applied Mathematics
“Symbolic” toolbox allows you to:
 Enter expressions in symbolic form with symbolic data
types.
 Expand or simplify symbolic expressions.
 Find symbolic roots, limits, minima, maxima, etc.
 Differentiate and integrate symbolic functions.
 Generate Taylor series of functions (among other tools).
 Solve algebraic and differential equations symbolically.
 Solve simultaneous equations (even some nonlinear).
 Do variable precision arithmetic.
 Create graphical representations of symbolic functions.
Creating Symbolic Variables
 In order to use the symbolic toolbox, you
must create symbolic variables.
 To create one symbolic variable, type:

x = sym('x');

 You can also use the syms command:

syms x;
Creating Multiple Variables
 To create several symbolic variables use
the syms command as follows:

syms K T P0;

 This creates the symbolic variables K, T,


and P0; execute the command whos to
check that this is indeed the case.
Creating a symbolic expression with
symbolic variables

 To create an expression using existing


symbolic variables, type:

P = P0*exp(K*T)

 This creates a symbolic expression that


includes the exponential function. It could
represent the exponential growth of a
population.
Creating an expression with sym()

 You can also create symbolic expressions


with the sym() command:

E = sym('m*c^2')
Symbolic equations

 It is possible to write equations with the


symbolic toolbox. Type the following:

ideal_gas_law = sym('P*V = n*R*Temp')

 This equation is the ideal gas law.


Manipulating symbolic expressions
 numden()
 expand()
 factor()
 collect()
 simplify()
 simple()
 poly2sym()
numden()
The numden() command is used to
separate the numerator and denominator
of a quotient.
Use numden() on the following expression:
y=2*(x + 3)^2/(x^2 + 6*x + 9)
[numerator, denominator]=numden(y)

numerator=
2*(x + 3)^2
denominator=
(x^2 + 6*x + 9)
expand()
 expand() is used to expand an expression
by expanding the products of factors in an
expression.

 Expand the numerator of y:


expand(numerator)
expand(numerator

ans=
2*x^2 + 12*x + 18
factor()
 The factor() command is used to factor an
expression into a product of terms.

Example: Factor the expression for the


denominator.
factor(denominator)

ans=
(x + 3)^2
simplify()
 The simplify() command uses the Maple
simplification algorithm to simplify each
part of an expression.
 Enter the expression:

b=sym('3*a - (a + 3)*(a - 3)^2');


simplify(b)

ans=
12*a - a^3 + 3*a^2 - 27
simple()
 The simple() command executes many
techniques to simplify an expression; its
ans is the simplest expression.

simple(b)

ans =
3*a - (a + 3)*(a - 3)^2

Note: The simple() command displays the results of all


simplification methods; only the final result, i.e., the
answer (ans) is shown here.
poly2sym()
 The poly2sym() function uses an array of
coefficients to create a polynomial:
a=[1,3,2];
b=poly2sym(a)

b=
x^2 + 3*x + 2

 The function sym2poly() is the inverse of


poly2sym().
solve()
 The solve() function sets an expression
equal to zero, then solves the equation
for its roots.

E1=x^2 - 9
solve(E1)

ans=
3
-3
Hands on

solve('a*x^2 + b*x + c')

ans =
1/2/a*( -b + (b^2 - 4*a*c)^(1/2))
1/2/a*( -b - (b^2 - 4*a*c)^(1/2))

Note: The expression is in single quotes; if


the symbolic variables in the expression
have not been defined previously, then the
single quotes are necessary.
Hands on

solve('a*x^2 + b*x + c', 'a')

ans =
-(b*x + c)/x^2

Note that this solves the expression for “a”.


Systems of equations
 You can use solve() to find the solution of
a system of equations.
one=sym('3*x + 2*y – z = 10');
two=sym('-x + 3*y + 2*z = 5');
three=sym('x – y – z = -1');
[x,y,z]=solve(one,two,three)

x= y= z=
-2 5 -6

Note that the solve function produces symbolic output. You can change the
output to numerical values with the double() command.
Substitution with subs()
 The subs() command allows you to
substitute a symbol with another symbol or
assign a number to a variable.

syms a b c x y;
quadratic = a*x^2 + b*x + c;
yquadratic = subs(quadratic,x,y)

yquadratic =
a*y^2 + b*y + c
Multiple substitutions
 You can use the subs() command to do
multiple substitutions in one command.
This is done by grouping the variables and
their substitutes (other variables or
numerical values) in braces.
subs(symbolic_function, {substitutant}, {substitute})

subs(quadratic, {a,b,c,x}, {1,2,3,4})

ans =
27
Plotting symbolical functions
 Plotting symbolic functions in MATLAB is
done with the ezplot() set of commands.
 The syntax of ezplot() when y is a function
of x is:
ezplot(y) x 2-2 x+3

50
y = sym('x^2 – 2*x + 3');
ezplot(y) 40

30

20

10

0
-6 -4 -2 0 2 4 6
x
Differentiation
 MATLAB allows you to differentiate
symbolic functions with the diff() command.
 The syntax of diff(), when f is a symbolic
function of the variable x and n is the order
of the derivative to be determined, is:

diff(f,'x' ,n)

diff(y,'x',1)

ans = Try a second derivative. Your result


2*x-2 should be 2.
Integration
 MATLAB allows you to integrate symbolic
functions with the int() command. Either
definite integrals, with assigned numeric or
symbolic bounds, or indefinite integrals (note
that when you compute indefinite integrals, the constant of integration does
not appear explicitly).

int(y,'x',a,b)

int(y,'x')

ans = Try a definite integral for 1<x<2. Th


1/3*x^3-x^2+3*x result should be 7/3.
Integration constant
 If you want to display the integration
constant when applying the int() function,
you can do the following:
syms x y a
y = 2*x;
int(y,’a’,’x’)
ans =
x^2–a^2
Exercises
 Use the symbolic toolbox to solve the
following system of equations:
x + 2y - z = 4
3x + 8y + 7z = 20
2x + 7y + 9z = 23

 The velocity of a car is v = t^2 – 3t + 5. Find


the displacement for 1<t<5 and the acceleration
at t=1.5. Plot the equations for distance,
velocity, and acceleration on one graph.
Summary
 Creating Symbolic Expressions
– sym(‘x’), syms x, expressions i.e. e=sym(‘m*c^2’)
 Manipulation
– numden, expand, factor, collect, simplify, simple, poly2sym
 Solutions
– solve, subs
 Plotting
– ezplot
 Differentiation
– diff(y, ‘x’, n)
 Integration
– int(y, ‘x’, a, b)
Ordinary Differential Equations

Dr. Litan Kumar Saha

250
Solution of Differential Equations
with MATLAB
 MATLAB has some powerful features for
solving differential equations of all types. We
will explore some of these features. The
approach here will be that of the Symbolic
Math Toolbox. The result will be the form of
the function and it may be readily plotted with
MATLAB.

251
ODE by Symbolic Math Toolbox
Symbolic Differential Equation Terms

2 n
dy d y d y
y 2 n
dt dt dt
y Dy D2y Dny

252
ODE by Symbolic Math Toolbox
 Solve DE below with MATLAB.

dy
+ 2y =
12 y (0) = 10
dt
>> y = dsolve('Dy + 2*y = 12', 'y(0)=10')
y = 6+4*exp(-2*t)

>> ezplot(y, [0 3])


>> axis([0 3 0 10])
253
ODE by Symbolic Math Toolbox

254
ODE by Symbolic Math Toolbox

dy
+ 2y =
12sin 4t y (0) = 10
dt
d2y dy y '(0) = 10
2
20 y (0) = 0
+ 2 + 5y =
dt dt
d2y dy y (0) = 10 y '(0) = 0
2
+3 + 2y =
24
dt dt

255
ODE by Symbolic Math Toolbox
 Solve DE below with MATLAB.

dy
+ 2y =
12sin 4t y (0) = 10
dt
>> y = dsolve('Dy + 2*y = 12*sin(4*t)',
'y(0)=10')
y = -12/5*cos(4*t)+6/5*sin(4*t)+62/5*exp(-2*t)
>> ezplot(y, [0 8])
>> axis([0 8 -3 10])
256
ODE by Symbolic Math Toolbox

257
Solve DE below with MATLAB.
2
d y dy
2
+ 2 + 5y =
20
dt dt
y (0) = 0 y '(0) = 10

>> y = dsolve('D2y + 2*Dy + 5*y = 20',


 'y(0) = 0', 'Dy(0) = 10')
y = 4+3*exp(-t)*sin(2*t)-4*exp(-t)*cos(2*t)

>>ezplot(y, [0 5]}
258
259
Solve DE below with MATLAB.
2
d y dy
2
+ 3 + 2y = 24
dt dt
y (0) = 10 y '(0) = 0
>> y = dsolve('D2y + 3*Dy + 2*y = 24',
'y(0)=10', 'Dy(0)=0')
y =
12+2*exp(-2*t)-4*exp(-t)

>> ezplot(y, [0 6])


260
261
Solving ordinary differential equations
 Ordinary differential equation can be solved
in MATLAB using functions like ode23 or
ode45.
 MATLAB’s ode23 function uses second- and
third-order RK functions to solve the ODE and
adjust step sizes.
 MATLAB’s ode45 function uses fourth- and
fifth-order RK functions to solve the ODE and
adjust step sizes..

262
Using ode Functions
 The functions are generally called in the
same way; ode45 is used as an example:
[t, y] = ode45(odefun, tspan, y0)
 y: solution array, where each column represents
one of the variables and each row corresponds to
a time in the t vector
 odefun: function returning a column vector of
the right-hand-sides of the ODEs
 tspan: time over which to solve the system
 y0: vector of initial values
Solving ordinary differential equations
 Ordinary differential equation can be solved
 For first order ODE, simply prepare a function
y’ = f(x) and name it as yprime.m, then solve
by [t,y]=ode23(@yprime, tspan,y0)
 Plot the graph to show the solution.
 For higher order ODE, rewrite it into a system
of first order ODE and solve similarly.

264
Solving ordinary differential equations
 To solve y’ - y – t = 0, y(0) = 0 the matlab
code yprime.m should be like,
function yp = yprime(y,t)
yp = y + t;
 Solve it by
 tspan=[0,10];
 y0 = 0;
 [t,y] = ode23(@yprime,tspan,y0)

 Plot the graph t vs y to show the solution


 plot(t,y)
265
Solving ordinary differential equations
 Another example to solve a 2nd order ODE, y'' + y' + y
+ t = 0, the matlab code yprime1.m should be like,
function yp=yprime1(y,t)
yp(1) = y(2);
yp(2) = -y(2) - y(1) -t;
 Solve it by
 tspan=[0,10];
 y0 = 0;
 [t,y] = ode23(@yprime1,tspan,y0)
 Plot the graph t vs the first and second column of y to
show the solution y and y’
 plot(t,y(*,1),y(*,2))
266
Example - Predator-Prey
dy1 dy2
 Solve: = 1.2y1 − 0.6y1 y2 = 0.8y2 + 0.3y1 y2
dt dt
with y1(0)=2 and y2(0)=1 for 20 seconds
 predprey.m M-file:
function yp = predprey(t, y)
yp = [1.2*y(1)-0.6*y(1)*y(2);…
-0.8*y(2)+0.3*y(1)*y(2)];
 tspan = [0 20];
y0 = [2, 1];
[t, y] = ode45(@predprey, tspan, y0);
figure(1); plot(t,y); figure(2);
plot(y(:,1),y(:,2));
Exercises
Solve the following differential equation of motion of
a nonlinear pendulum by MATLAB. Hence show the
displacement and velocity vs. time plot of the
pendulum in the same diagram with different graphic
objectives.
dθ2

2
+ ω sin θ =
2
0
dt
θ (0) = 1 θ '(0) = 0
268
Thank you!

271

You might also like