Matlab Practice Tutorial
Matlab Practice Tutorial
MATLAB Workshop
A. MATLAB built-in functions. MATLAB has many built-in mathematical functions, includ-
ing trigonometric, logarithmic, and hyperbolic functions, as well as functions for processing
arrays. Following are the some of the common mathematical functions
square root x. Question: Find square root of 5, 7, 15, 25. Also, find e2 .
• Logarithmic: log(x) - Natural logarithm; ln x. log10(x) - Common (base-10)
logarithm; logx = log10 x. Question: For several values of x and y, confirm that ln(xy)
= ln x + ln y.
• Complex: abs(x) - Absolute value; x. angle(x) - Angle of a complex number x.
conj(x) - Complex conjugate. imag(x) - Imaginary part of a complex number x.
real(x) - Real part of a complex number x. √ Question: Find the magnitude, angle,
real part, and imaginary part of the number 2 + 6i . (Answers: magnitude = 2.5149,
angle = 0.6245 rad, real part = 2.0402, imaginary part = 1.4705).
• Numeric: ceil(x) - Round to the nearest integer toward ∞. fix(x) - Round to
the nearest integer toward zero. floor(x) - Round to the nearest integer toward -∞.
round(x) - Round toward the nearest integer. sign(x) - Signum function: +1 if
x > 0; 0 if x = 0; -1 if x < 0.
• Trigonometric: cos(x) - Cosine; cos x. cot(x) - Cotangent; cot x. csc(x) -
Cosecant; csc x. sec(x) - Secant; sec x. sin(x) - Sine; sin x. tan(x) - Tangent; tan
x. (NOTE: x should be in radians.) Question : For several values of x in the range 0
≤ x ≤ 2 , confirm that sin2 x + cos2 x = 1.
• Inverse trigonometric - acos(x) - Inverse cosine; arccos x = cos−1 x. acot(x) -
Inverse cotangent; arccot x = cot−1 x. acsc(x) - Inverse cosecant; arccsc x = csc−1 x.
asec(x) - Inverse secant; arcsec x = sec−1 x. asin(x) Inverse sine; arcsin x = sin−1 x.
atan(x) - Inverse tangent; arctan x = tan−1 x. (NOTE: x should be in radians.)
Question : For several values of x in the range 0 ≤ x ≤ 2 , confirm that sin−1 x +
π
cos−1 x = .
2
B. User Defined Functions MATLAB also provides option to have user defined functions -
functions to perform tasks which are not available as built-in commands.Unlike a script file,
all the variables in a function file are local variables, which means their values are available
only within the function. Function files are useful when you need to repeat a set of commands
several times. They are the building blocks of larger programs.
To create a function file, open the Editor /Debugger. The first line in a function must begin
with a function definition line that has a list of inputs and outputs. This line distinguishes
a function file from a script file. Its syntax is as follows:
function [out1, out2,.., outN] = function name(inp1, inp2,.., inpM)
The output variables are those variables whose values are computed by the function, using
the given values of the input variables. Note that the output variables are enclosed in square
brackets (which are optional if there is only one output), while the input variables must be
enclosed with parentheses. The function name should be the same as the file name in
which it is saved (with the .m extension). The function is ”called” by typing its name at
the command line. The word function in the function definition line must be lowercase.
Before naming a function, you can use the exist function to see if another function has the
same name.
A. Relational Operators. MATLAB has six relational operators to make comparisons between
arrays. They are : < - Less than; <= Less than or equal to; > Greater than; >= Greater than
or equal to; == Equal to; = Not equal to. Note that the equal to operator consists of two
== signs, not a single ”=” sign as you might expect. The single = sign is the assignment,
or replacement, operator in MATLAB.
Question: Go the MATLAB command prompt. Assign value to two variables say x and y.
Then, apply the above relational operators and check the output.
B. Logical Operators and Functions. MATLAB has five logical operators, which are some-
times called Boolean operators. These operators perform element-by-element operations.
With the exception of the NOT operator (∼), they have a lower precedence than the arith-
metic and relational operators . The NOT symbol is called the tilde.
• Operator: ∼, Name: NOT, Definition: ∼ A returns an array of the same dimension
as A; the new array has 1s where A is 0 and 0s where A is nonzero.
• Operator: & , Name: AND , Definition: A & B returns an array of the same
dimension as A and B; the new array has 1s where both A and B have nonzero elements
and 0s where either A or B is 0.
• Operator: |, Name: OR , Definition: A | B returns an array of the same dimension
as A and B; the new array has 1s where at least one element in A or B is nonzero and
0s where A and B are both 0.
• Operator: &&, Name: Short-Circuit AND , Definition: Operator for scalar logical
expressions. A && B returns true if both A and B evaluate to true, and false if they do
not.
• Operator: ||, Name: Short-Circuit OR, Definition: Operator for scalar logical ex-
pressions. A —— B returns true if either A or B or both evaluate to true, and false if
they do not.
Question: (a) Go to MATLAB command prompt. Set two vectors x = [0, 3, 9] and y =
[14, -2, 9]. Then observe the output of z = ∼x, u = ∼x > y, = ∼(x > y). (b) Set x = [5, -3,
0, 0] and y = [2, 4, 0, 5]. Then observe the output of z = x & y. (c) What will the result of
z = 1 & 2 + 3. (d) Let x = [6, 3, 9] and y = [14, 2, 9] and let a = [4, 3, 12]. Then, what is
the output of the expression z = (x > y) & a.
C. Conditional Statements if else statements. The MATLAB conditional statements en-
able us to write programs that make decisions. Conditional statements contain one or more
of the if, else, and elseif statements. The end statement denotes the end of a condi-
tional statement, just as the period was used in the preceding examples. These conditional
statements have a form similar to the examples, and they read somewhat like their English-
language equivalents. The if statement’s basic form is
if logical expression
statements
end
Every if statement must have an accompanying end statement. The end statement marks
the end of the statements that are to be executed if the logical expression is true.
A space is required between the if and the logical expression, which may be a scalar,
Note that each if statement has an accompanying end statement. When more than one
action can occur as a result of a decision, we can use the else and elseif statements along
with the if statement. The basic structure for the use of the else statement is
if logical expression
statement group 1
else
statement group 2
end
Question: (a) Write a function take an input x and computes its square root which is the
output. If the number is negative then a message has to be printed that the number is less
than 0; (b) Now instead of scalar x input a vector x e.e. x = [4, -9, 25] and find the
square root. Your code should print an error message if the number is negative. (c) Write
a function which computes square root of a scalar x if it is between 1 and 10, log10 if it is
greater than 10 and inverse it is less than 0. If it is 0 then a error message should be printed.
(d) Given a number x and the quadrant q(q = 1, 2, 3, 4), write a program to compute sin−1 (x)
in degrees, taking into account the quadrant. The program should display an error message
if kxk > 1.
D. for loops. A loop is a structure for repeating a calculation a number of times. Each repeti-
tion of the loop is a pass. MATLAB uses two types of explicit loops: the for loop, when
the number of passes is known ahead of time, and the while loop, when the looping process
must terminate when a specified condition is satisfied and thus the number of passes is not
known in advance. The typical structure of a for loop is
for loop variable = m:s:n
statements
end
Nesting of for loop: The for loop can be nested (shown below for two levels). for
loop variable 1 = m1:s1:n1
statements group 1
for loop variable 2 = m2:s2:n2
statements group 2
end
end
The expression m:s:n assigns an initial value of m to the loop variable, which is incremented
by the value s, called the step value or incremental value. The statements are executed
once during each pass, using the current value of the loop variable. The looping continues
until the loop variable exceeds the terminating valuen. Note that a for statement needs
an accompanying end statement. The end statement marks the end of the statements that
are to be executed. A space is required between the for and the loop variable, which
may be a scalar, a vector, or a matrix, although the scalar case is by far the most common.
Please note that the if..else construct can also be used in the for loop.
Question: (a) Write a script file to compute the sum of the first n terms in the series
5 k 2 − 2 k, where k = 1, 2, 3, ..., n. (b) Write a script file to compute the square root and
square of first n numbers starting from 1 and difference between them being d. For e.g. First
30 numbers
√ stating from 1 in step of 5 (=d). (c) Write a script file to plot the function
y = 15 4x + 10 if x ≥ 9, y = 10 x + 10 if 0 ≤ x < 9, and y = 10 if x < 9 for −5 ≤ x ≤ 30.
E. while loops. The while loop is used when the looping process terminates because a specified
condition is satisfied, and thus the number of passes is not known in advance. The typical
structure of a while loop is as follows
while logical expression
statements
end
MATLAB first tests the truth of the logical expression. A loop variable must be included
in the logical expression. If the logical expression is true, the statements are
executed. For the while loop to function properly, the following two conditions must occur:
1. The loop variable must have a value before the while statement is executed.
2. The loop variable must be changed somehow by the statements.
The statements are executed once during each pass, using the current value of the loop
variable. The looping continues until the logical expression is false.
Question: (a) Write a script file to determine the number of terms required for the sum of
the series 5k 2 − 2k, k = 1, 2, 3, ..., to exceed 10000. What is the sum for this many terms?
(b) Determine how long it will take to accumulate at least Rs. 10000 in a bank account if you
deposit Rs. 500 initially and Rs. 500 at the end of each year, if the account pays 5 percent
annual interest.
• Command: axis([xmin xmax ymin ymax]) - Sets the minimum and maximum
limits of the x and y axes.
– axis square selects the axes’ limits so that the plot will be square.
– axis equal selects the scale factors and tick spacing to be the same on each axis.
– axis auto returns the axis scaling to its default auto scaling mode in which the
best axes’ limits are computed automatically.
Type help axis in the command prompt to see the full list of variants.
• Command: fplot(function,[xmin xmax]) - Performs intelligent plotting of
functions, where function is a function handle that describes the function to be plotted
and [xmin xmax] specifies the minimum and maximum values of the independent
variable. The range of the dependent variable can also be specified. In this case the
syntax is fplot(function, [xmin xmax ymin ymax]).
• Command: grid - Displays gridlines at the tick marks corresponding to the tick
labels.
• Command: plot(x,y) - Generates a plot of the array y versus the array x on
rectilinear axes.
• Command: plot(y) - Plots the values of y versus their indices if y is a vector. Plots
the imaginary parts of y versus the real parts if y is a vector having complex values.
• Command - polyval(p,x) - Evaluates the polynomial p at specified values of its
independent variable x.
• Command: print - Prints the plot in the Figure window. Type help print in the
command prompt to see the full list of variants.
• Command: title(text) - Puts text in a title at the top of a plot.
• Command: xlabel(text) - Adds a text label to the x axis (the abscissa).
• Command: ylabel(text) - Adds a text label to the y axis (the ordinate).
• Command: hold - The hold command creates a plot that needs two or more plot
commands. It essentially freezes the current plot for subsequent graphics commands. It
is also needed when one needs to keep the current plot and plot the next figure on top
of the current plot. hold off turn off this feature. If hold is off then all new plots
are drawn on the current plot which is lost.
• Command: legend(leg1,leg2,...) - Creates a legend using the strings leg1,
leg2, and so on and enables its placement with the mouse.
• Command: text(x,y,text) - Places the string text in the Figure window at a
point specified by coordinates x, y.
• Command: plot(x,y,u,v) - Plots, on rectilinear axes, four arrays: y versus x and
v versus u.
Question (a) (a) Plot sin x and cos x for 0 ≤ x ≤ 2π. Label the x axis ’x’, y axis as ’Value
of sin(x) or cos(x)’ and put a legend for each. Plot the sin plot in red and cos plot in blue.
(b) Plot sin x versus cos x √for 0 ≤ x ≤ 2π. Label the x axis ’sin(x)’, y axis as ’cos(x)’(b)
Plot the equation y = 0.4 1.8x for 0 ≤ x ≤ 35 and 0 ≤ y ≤ 3.5. (c) Plot the function
3x5 + 2x4 − 100x3 + 2x2 − 7x + 90 over the range −6 ≤ x ≤ 6 with a spacing of 0.01.
In ease case above print the figures in both ’jpeg’ and ’eps’ format with resolution of 400 dpi.
B. Additional command and plot types. MATLAB can create figures that contain an array
of plots, called subplots. These are useful when you want to compare the same data
plotted with different axis types, for example. The MATLAB subplot command creates
such figures. You can use the subplot command to obtain several smaller ”subplots” in the
same figure. The syntax is subplot(m,n,p). This command divides the Figure window
into an array of rectangular panes with m rows and n columns. The variable p tells MATLAB
to place the output of the plot command following the subplot command into the pth pane.
For example, subplot(3,2,5) creates an array of six panes, three panes deep and two
panes across, and directs the next plot to appear in the fifth pane (in the bottom left corner).
Question: (a)Use subplot command to plot the functions y = e−1.2x sin(10x + 5) for 0 ≤
x ≤ 5 and y = |x3 − 100| for −6 ≤ x ≤ 6.
C. Specialized plot commands There are other type of plots possible in MATLAB. They are
as follows
• Command: bar(x,y) - Creates a bar chart of y versus x.
• Command: loglog(x,y) - Produces a log-log plot of y versus x.
• Command: plotyy(x1,y1,x2,y2) - Produces a plot with two y axes, y1 on the
left and y2 on the right.
• Command: polar(theta,r,type) - Produces a polar plot from the polar coordi-
nates theta and r, using the line type, data marker, and colors specified in the string
type.
use meshgrid command to generate a field of x and y values. Type help meshgrid for
more details.) (c) Generate the contour plot for the surface generated in part (b) using the
command contour(x,y,z).