Vous êtes sur la page 1sur 14

MATLAB Pamphlet with Exercises

Section 0: A Few Basics

We start by using MATLAB to perform addition and scalar multiplication of vectors in two and
three dimensions. Several MATLAB commands are introduced via these calculations. MATLAB
commands and output are shown using Verdana font.

ENTERING VECTORS AND VECTOR OPERATIONS

Begin a MATLAB session. We now discuss how to enter a vector into MATLAB. The syntax is
straightforward. To enter the row vector 𝒙
⃑ = [1 −2 3], type
>> x = [1 -2 3]
and MATLAB returns
x=
1 -2 3
MATLAB echoes the x vector for you.
Note: this pamphlet shows MATLAB entries and returns in combination, when appropriate.

To demonstrate the syntax of vector addition and scalar multiplication, enter a second vector, with
a semicolon at the end, as
>> y = [3 2 -1];
The sum of x and y follows from
>> x+y
ans =
4 0 2
Similarly, calculate 2𝒙
⃑ by typing
>> 2*x
ans =
2 -4 6
Here we mention two fundamental aspects concerning MATLAB.
1) When a vector or a number is entered, MATLAB will automatically echo whatever is entered.
This echoing can be suppressed by appending a semicolon, ; , to the line. For example, type
>> z = [1 0 1];
and MATLAB responds with a new line and the command prompt, >>.
2) MATLAB stores the information obtained by algebraic manipulation in a new vector. If a
variable name is not provided, MATLAB uses the default variable name ans.
For example, enter the following
>> 2*x+4*y-3*z
ans =
11 4 -1

1
MATLAB Pamphlet with Exercises

To use the result of a calculation later in a MATLAB session, we want to name the result. Create a
new vector w by typing
>> w = 2*x+4*y-3*z
w=
11 4 -1
Now w can be used in future calculations.
To create a column vector in MATLAB we separate the entries in a vector with semicolons. Enter
>> s = [4;-5;6]
s=
4
-5
6
The s vector is a column vector. MATLAB will usually not perform incorrect operations. Enter
>> s+x
Error using +
Matrix dimensions must agree.
MATLAB returns an error because a row vector and column vector cannot be added together.

ENTERING MATRICES

Matrices are entered into MATLAB row by row, with rows separated by semicolons or by line
1 2 3
returns. To enter the matrix, 𝑨 = [4 5 6], type the following in MATLAB
7 8 9
>> A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9

MATLAB has several methods for addressing the entries of a matrix. You can directly access
individual entries, individual rows or columns, or sub-matrix blocks. To access the specific matrix
element 𝑎32 , type
>> A(3,2)
ans =
8
To select the 3rd column in the matrix A and assign it to the vector c3, type
>> c3 = A(:,3);
The colon, : , is used to select all of the elements in the 3rd column. Verbally you can think of this
command as, “Take all of the rows in the 3rd column.” The 2nd row of A is retrieved by

2
MATLAB Pamphlet with Exercises

>> r2 = A(2,:)
r2 =
4 5 6
which is verbally, “In the 2nd row, take all of the columns.” This notation is powerful and can be
used to complete algebraic computations. Consider the MATLAB expression for building a new
vector as the sum of the 1st and 3rd rows of A
>> A(1,:)+A(3,:)
ans =
8 10 12
This notation can be used to grab a vector or sub-matrix from a matrix. Enter the following
>> A(1:2,2:3)
ans =
2 3
5 6
and ans is the matrix made from the first two rows and last two columns in A.

Another powerful feature of MATLAB’s matrix manipulation is the idea of replacing current values.
A simple example replaces the value 7 in the A matrix with a value of 8.
>> A(3,1) = 8
A=
1 2 3
4 5 6
8 8 9
To replace the upper, right 2 × 2 sub-matrix in A, enter
>> A(1:2,2:3) = [0 1; 1 0]
A=
1 0 1
4 1 0
8 8 9

A FEW MORE ITEMS

The format command is used to change the format of the numbers shown on the screen. There are
several options for the format command, and the more prevalent are listed below. Entering two
commands on the same line is allowed, if the commands are separated by a semicolon or a comma.
Enter the following commands and consider their differences. (Note: the up arrow on your
computer can be used to access previously executed commands.)
format shortg; sqrt(2)/(100*pi)
format longg; sqrt(2)/(100*pi)
format rat; sqrt(2)/(100*pi)

3
MATLAB Pamphlet with Exercises

The format rat option can be very handy. This format type displays output as rational numbers or
approximate rational numbers whenever possible.

Our final topic for discussion is MATLAB’s help command. Typing help followed by a function
name, e.g. help format, provides a description of the function and implementation instructions.

This concludes our brief introduction to MATLAB. MATLAB is an industry standard software
package, and it includes several built-in tutorials. You need to familiarize yourself with the basics of
MATLAB because we will use the program extensively in this course. To continue learning about
MATLAB follow these steps:
1) Open a MATLAB session
2) Select Help from the menu bar
3) Once inside MATLAB select the topic MATLAB
4) Now select Getting Started or Examples to learn more about MATLAB

** EXERCISES SECTION 0
1) Enter "help :" and use the : operator to build an integer vector from 1 to 100.
2) Use the : operator to build a vector containing integers in the interval [–10, 10].
4 −6
3) Enter the matrix 𝑪 = [ ]. Replace the −6 with a 2 and replace the 7 with a −5.
7 0

Section 1: Built-in Functions and Scripts

MATLAB stands for Matrix Laboratory and is designed to work using arrays, i.e. vectors, matrices,
etc., as its fundamental building blocks. MATLAB also includes a wide variety of built-in functions
including basic math functions such as sine and natural log. A frequently used command is clear.
The command can be used to clear specific variables, e.g. clearing the variables x, y, t, and A,
>> clear x y t A
or can be used to clear all variables at once via
>> clear all

USING BUILT-IN FUNCTIONS

Begin a MATLAB session and enter the vector 𝒙


⃑ = [1 −2 3].
>> x = [1 -2 3];
Apply the cos() function to x and note how MATLAB applies the cos() to each entry in the vector.
>> cos(x)
ans =
0.5403 -0.41615 -0.98999

4
MATLAB Pamphlet with Exercises

As with all built-in MATLAB functions, the help command can be used to find a description of the
function. Often these descriptions include links to similar functions. For example, enter
>> help cos
cos Cosine of argument in radians.
cos(X) is the cosine of the elements of X.
See also acos, cosd. …

Many other useful functions are also available in MATLAB. One of the most commonly used is the
linspace() command which generates a vector of linearly spaced numbers. Enter
>> t = linspace(0,10,11)
t=
0 1 2 3 4 5 6 7 8 9 10
This linspace() command generates 11 points in the interval [0,10]. This command is often used
in conjunction with the plot() command to plot a function. Replace the array t by entering
>> t = linspace(0,4*pi,1001);
Now t is an array containing 1001 entries that are equally spaced in [0,4𝜋]. We use the semicolon
to suppress the echo and avoid seeing the 1001 entries in t. The generic array entry t(k), written
as 𝑡𝑘 , is given by
4𝜋
𝑡𝑘 = (𝑘 − 1) for 𝑘 = 1,2, … , 1001
1000
This is easy to verify. Use MATLAB to find 𝑡394 using the formula and check it against t(394).
>> t394 = 4*pi/1000*393
t394 =
4.9386
>> t(394)
ans =
4.9386

Continuing, we build an array of values for the cosine.


>> y = cos(t);
The y array has 1001 entries, and each entry corresponds to the cosine of the corresponding entry
in t. We will verify at least one point by checking the cosine value at the specific entry t(394).
>> cos(t(394))
ans =
0.22427
>> y(394)
ans =
0.22427
With the arrays t and y, we can now plot these points and graph the function
cos(𝑡) with 𝑡 ∈ [0,4𝜋]

5
MATLAB Pamphlet with Exercises

The MATLAB plot function does nothing more than graph the points in the arrays (pairwise) and
connect the consecutive points with straight lines. Enter
>> plot(t,y)
Notice that MATLAB opens a new figure window for the plot. This figure can now be called to the
front of the screen with the command figure(1).

ALWAYS USE SCRIPTS

A MATLAB script is a *.m file that contains several lines of MATLAB code. Using a script offers an
efficient way to program algorithms that require more than a single command. To create a script in
MATLAB R2016, under the HOME tab select “New” and then “Script.” An editor window will
appear, and a new file, named “Untitled,” will appear in its own tab. This is a script file (or script
for short), and it can be used to hold and execute several commands. While the array is the basic
building block within MATLAB, the script is the basic building block for programming in MATLAB.
Type the following commands into the script
clear all
t = linspace(0,4*pi,1001);
y = cos(t);
figure(1);
plot(t,y);
xlabel('t');
ylabel('cos(t)');
title('t vs cos(t)');

Now save the file to your directory and call the file scriptTest.m. On the command line type
>> scriptTest
This script will execute all the commands and a plot will appear. At this point it is easy to plot a
different function. In the script file change cos(t) to sin(t), save the file again, and execute the file.
Scripts offer an efficient way to program algorithms in MATLAB. You can quickly change any part
of a script file, save the file, and rerun the file.

To organize your work, include comments within your script files. To put a comment into a file use
the % sign. For example, put the following comments into your script:
% t is a vector of inputs for plotting the vector y
% y is a vector built as a function evaluation of the values in t
Comments can help you recall your work after a long absence from the script. Comments can also
be used to explain your program to others.

MATLAB has a plethora of built-in functions covering a wide variety of topics. These functions
amount to a new vocabulary, and you will learn several of these functions as the course progresses.
Following are some practice problems using many new MATLAB functions. Remember when you

6
MATLAB Pamphlet with Exercises

do not know how to use a function, use the help command to learn the syntax. This is the method
everyone uses when they face an unknown function, so you want to be comfortable using help.

** EXERCISES SECTION 1 A
Before starting a new problem that uses the same variables, you want to clear the variables using
the clear command, e.g. clear x y f or clear all.
1) Use the sqrt() command to find the values of: √𝑥 with 𝑥 = 1,2,3, … ,10. Use plot() to plot the
values of 𝑥 vs. √𝑥
2) Use the abs() command to find the values of: |𝑥| with 𝑥 = −5, −4, −3, … , 3, 4, 5. Use plot() to
plot the values of 𝑥 vs. |𝑥|
3) Use both plot() and rand() to plot 1000 uniformly distributed random numbers in the interval
(0,1) as blue dots.
4) Use cosh() to find the values of: cosh(𝑥) with 𝑥 = 1,2,3, … ,100. Use both plot() and
semilogy() to plot the values of 𝑥 vs. cosh(𝑥).
5) Use exp() to find the values of: 𝑒 𝑥 with 𝑥 = 1,2,3, … ,100. Use both plot() and semilogy() to
plot the values of 𝑥 vs. 𝑒 𝑥 .
6) Use both plot() and randn() to plot 1000 normally distributed random numbers, with a mean
of zero and a standard deviation of 1, as red dots.

USING THE “.” OPERATOR

Since MATLAB works with arrays as its fundamental building blocks, some seemingly innocuous
statements will not work as expected. Build a linearly spaced vector as
>> t = linspace(0,10,11);
Now we want to find 𝑡 2 . The following attempt seems reasonable, but it generates an error
>> y = t^2
Error using ^
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead.
Within the error text is the answer to our problem. It says to use “.^” to compute elementwise
powers. In general MATLAB uses the dot “.” to imply elementwise computation. Our attempt to
square the entries in t was really attempting the vector-vector multiplication t*t. We cannot
multiply vectors in this way. Elementwise computation will apply the requested calculation to each
element within the array
>> y = t.^2
y=
0 1 4 9 16 25 36 49 64 81 100
For another example, we will compute 𝑤 = 𝑡 cos(3𝑡) with the same array t. Calculating 3*t is no
problem since this calculation is well defined. Similarly, cos(3*t) offers no issues as we have seen.
However, t*cos(3*t) is an attempt to multiply the vector t times the vector cos(3*t), giving

7
MATLAB Pamphlet with Exercises

>> w = t*cos(3*t)
Error using *
Inner matrix dimensions must agree.
In this situation, we really want to multiply elementwise with t and cos(3*t). Thus, we need
>> w = t.*cos(3*t)
w=
Columns 1 through 6
0 -0.98999 1.9203 -2.7334 3.3754 -3.7984
Columns 7 through 11
3.9619 -3.8341 3.3934 -2.6292 1.5425

** EXERCISES SECTION 1 B
7) Calculate and plot the values for 𝑥 3 with 𝑥 = −5, −4, … , 0, … , 4, 5.
8) Calculate and plot the values for 𝑥 √𝑥 with 𝑥 = −5, −4, … , 0, … , 4, 5.
9) Calculate and plot the values for |cos(𝑥)𝑒 𝑥 | with 𝑥 ∈ [−1,1].

CREATING INLINE FUNCTIONS USING @()

MATLAB offers the ability to create your own inline functions. These are not to be confused with
user-defined functions which will be addressed later. An inline function is a way to combine built-
in functions for easier coding. For example, we can build an inline function for
𝑡 2 cos(𝑡)
𝑓(𝑡) =
3𝑡 − 5
The inline function has a function name, an independent variable(s), and the function itself. For our
example, we have
>> f = @(t) t.^2.*cos(t)./(3*t-5)
Notice that we need to include elementwise operations because the input variable may be a vector
or matrix. After entering the above inline function, we can calculate values in the natural way. To
find 𝑓(0) simply type
>> f(0)
ans =
0
>> f(2)
ans =
-1.66458734618857
Define several points in the interval [−1,1] and calculate the resulting values for 𝑓.
>> x = linspace(-1,1,101);
>> y = f(x)

8
MATLAB Pamphlet with Exercises

y=
Columns 1 through 6
-0.067538 -0.067376 -0.067076 -0.066642 -0.066078 -0.06539
Columns 7 through 12
-0.064582 -0.06366 -0.062628 -0.061491 -0.060256 …
As we have seen previously, this function can be plotted easily.
>> plot(x,y)

** EXERCISES SECTION 1 D
Use the @() command to build inline functions and solve the following problems. Use a script to
enter your commands.
10) Evaluate the function 𝑓(𝑥) = √𝑥 cos(3𝑥) at 𝑥 = −5, −4, … , 0, … , 4, 5 and plot the 𝑥 vs. 𝑓(𝑥) on
a scatter plot using blue asterisks.
−𝑥+√𝑥 2 −25
11) Evaluate the function 𝑓(𝑥) = at 𝑥 = −12, −11, … , 0, … , 11, 12 and plot the 𝑥 vs. 𝑓(𝑥)
2
on a scatter plot using red points.
12) Evaluate the function 𝑓(𝑥) = 2𝑥 (36 − 𝑥 2 ) for 𝑥 ∈ [−6,6] and plot the 𝑥 vs. 𝑓(𝑥) at 100,001
points on a semilog plot.

Section 2: Looping

Computers are basically good at 1 thing, and they are really bad at 1 thing. Starting with the good:
 Computers are excellent at rapidly repeating the same task over and over and over again
Now for the bad:
 Computers are terrible at solving problems – they cannot think … at all
The bottom line is quite simple: A computer can only be programmed to solve a problem that you
already know how to solve.

Because the primary strength of a computer is rapid, repetitive computation, we need to learn how
to add repetitive tasks into a program. To this end, we investigate the two primary looping
commands in MATLAB: while … end and for … end. The syntax for these commands is straight
forward, and you should look at them by typing
>> help while
>> help for

9
MATLAB Pamphlet with Exercises

WHILE LOOPS IN MATLAB

To demonstrate the while … end command, enter the following into a script:
clear all
iter = 1; % iter is the current iteration of the loop
itSum = 0; % itSum is the sum of the iterations
while iter < 101
itSum = itSum + iter;
iter = iter + 1;
end
itSum

This loop sums the numbers from 1 to 100. Using a while … end construct in this situation is a
poor choice. The for … end command is more efficient. Consider the following code which
performs the same operation with two fewer lines.
clear all
itSum = 0; % itSum is the sum of the iterations
for iter = 1:100
itSum = itSum + iter;
end
itSum

The while … end construct works better when the number of required iterations to solve a
problem is unknown. Consider the following problem.
How many fractions of the form 1⁄𝑛 with 𝑛 ∈ ℕ must be summed before the total exceeds √1000?
To solve this problem a while loop is ideal. Enter this solution into a script and find the answer.
clear all
iter = 1; % iter is the current iteration of the loop
itSum = 0; % itSum is the sum of the iterations
stopCrit = sqrt(1000); % stopCrit is the stopping criteria for the while loop
while itSum < stopCrit
itSum = itSum + 1/iter;
iter = iter + 1;
end
iter-1

Oops, we have a problem. Hit the ctrl key and the letter c simultaneously to cancel the current
command, i.e. ctrl+c. Due to programming and logical errors, we are often forced to use ctrl+c
in order to stop a runaway computation.

10
MATLAB Pamphlet with Exercises

This program was running for too long. As with many while loops, we have the potential for an
infinite (or really long) loop. To abate this issue, we generally use the break command. Within the
while … end command add the following line:
if iter > 1e8, break, end
Note: we discuss the if … end command in the next section, but here we use it to breakout of the
while … end if the number of iterations exceeds 100 million = 1e8.
Now rerun the script. The program sums the first 100 million numbers of the from 1⁄𝑛 with 𝑛 ∈ ℕ
and then it breaks out of the loop.
Consider the modified problem.
How many fractions of the form 1⁄𝑛 with 𝑛 ∈ ℕ must be summed before the total exceeds √300?
By changing the stopping criteria we can show the power of a while loop. Modify the script with
stopCrit = sqrt(300)
Re-executing the script gives
ans =
18686136
Thus, a sum of the first 18,686,136 numbers of the form 1⁄𝑛 is slightly greater than √300. This
leads to another interesting question. What is the difference shown below?
18686136
1
( ∑ ) − √300
𝑛
𝑛=1
At the end of the previous script, simply add the line
theDiff = itSum-stopCrit
Re-executing the script gives
theDiff =
3.2452e–08

FOR LOOPS IN MATLAB

The for … end loop is a good choice whenever the number of looping iterations is known. The
earlier example is repeated here.
clear all
itSum = 0; % itSum is the sum of the iterations
for iter = 1:100
itSum = itSum + iter;
end
itSum
This loop sums the integers from 1 to 100.
As another example of loops, consider the plotting refinements of the function sec(𝑡) on the interval
𝑡 ∈ [0,2].

11
MATLAB Pamphlet with Exercises

clear all
for jj = 1:10
t = linspace(0,2,2^jj);
figure(jj);
plot(t,sec(t));
end
This script opens 10 figures, numbered 1 through 10, and plots the secant function at a variety of
points. Note that the plot function connects data points with straight lines.
Change the plot command to the following
plot(t,sec(t),'k.');
Now the script replots the 10 figures without lines.

** EXERCISES SECTION 2
Use the appropriate looping command to solve these problems.
1) The following series converges. Estimate the limit of the series to 10 significant figures.

1
∑ where 𝑛 ∈ ℕ
𝑛5
𝑛=1
2) Find the value of the number created using the following pattern
1 ∗ 2 ∗ 3 + 2 ∗ 3 ∗ 4 + 3 ∗ 4 ∗ 5 + ⋯ + 499 ∗ 500 ∗ 501
3) Find the value of the number created using the following pattern
13.0 + 22.9 + 32.8 + ⋯ + 211.0
4) Find the minimum number of terms in the following pattern
4 5 6
𝑏 = + + +⋯
1 2 3
such that the number 𝑏 is greater than 𝑒 . 5

Section 3: Decisions

MATLAB contains a few decision type commands, but we focus only on the if … elseif … end
command. This command is straightforward and operates in the natural way. Enter the following
commands into a script
clear all
k = 10*rand(1) % a uniform random number between 0 and 10
if k <= 5
disp('k is less than or equal to 5');
else
disp('k is greater than 5');
end

12
MATLAB Pamphlet with Exercises

This is a simple decision that determines if the randomly generated value of 𝑘 ∈ (0,10) is greater
than or less than 5. The if … elseif … end command is often combined with a loop. Try this
clear all
totLo = 0; % total count of numbers less than 1
totMid = 0; % total count of numbers between 1 and 9
totHi = 0; % total count of numbers greater than 9
itMax = 100;
for ii = 1:itMax
k = 10*rand(1); % a uniform random number between 0 and 10
if k <= 1
totLo = totLo +1;
elseif k >= 9
totHi = totHi +1;
else
totMid = totMid+1;
end
end
percentLo = totLo/itMax
percentMid = totMid/itMax
percentHi = totHi/itMax

Now the decision has been expanded to consider 3 possible cases, namely 𝑘 ≤ 1, 1 < 𝑘 < 9, and
𝑘 ≥ 9. After the loop is run itMax times, the percentage of numbers in each interval is calculated
and shown on the screen. Notice how the script has been generalized so the number of iterations
can be changed quickly.

It is important to realize that the while loop is nothing more than a for loop that includes a built in
if … end command. Consider this generic loop
while z < stopCrit
z=…
end
compared with this version
for ii = 1:1000
z=…
if z < stopCrit
break
end
end

13
MATLAB Pamphlet with Exercises

The primary difference is that the for loop has a maximum number of iterations built into the
looping variable, ii. Thus, for and while loops are generally interchangeable, and a programmer
selects the more efficient for a given problem.

** EXERCISES SECTION 3 A
To solve the following problems, use the if … elseif … end command in combination with loops
and other functions as required.
1) Count the number of natural numbers from 1 to 1e6 for which the following is satisfied
1
|cos(𝑛)| < where 𝑛 = 1, 2, … , 1000000
𝑛
2) Find the natural numbers that satisfy the inequality in problem 1).
3) Evaluate the function 𝑓(𝑥) = sin(7𝑥) at 𝑥 = −50, −49, … , 0, … , 49, 50. Find the 𝑥 values for
which the function value 𝑓(𝑥) is less than −0.95.
4) Count the number of integers between −1000 and 1000 for which the following is satisfied
mod(𝑛, 𝜋) > 3 where 𝑛 = −1000, −999, … , 0, … , 999, 1000

** EXERCISES SECTION 3 B
To solve the following problems, use the if … elseif … end command in combination with loops
and other functions as required.
5) Generate a vector containing 100 uniformly distributed random numbers in (0,1), and build a
vector containing all of the numbers in the interval [0.6, 0.7]. Hint: use the and() command to
apply both conditions simultaneously.
6) Bin the natural numbers from 1 to 1,000,000 according to their cosine function evaluation.
Create 4 bins using the following rules:
count 𝑛 in bin A if cos(𝑛) > 0.5
count 𝑛 in bin B if 0 < cos(𝑛) < 0.5
count 𝑛 in bin C if −0.5 < cos(𝑛) < 0
count 𝑛 in bin B if cos(𝑛) < −0.5
Exactly how many numbers are in each bin?
7) Find all of the numbers between 1 and 1000 that have either 23 or 29 as a factor.
8) Find the first number 𝑥 as 𝑥 = 0 → 𝜋 such that 𝑥 > cos(𝑥). Determine the value of 𝑥 to 12
decimal places of accuracy.

14

Vous aimerez peut-être aussi