Вы находитесь на странице: 1из 11

Basic Syntax and Command-Line Exercises

The following exercises are meant to be answered by a single MATLAB command. If


the command is too complicated, feel free to break it up over two or more lines.
1. Create a vector of the even whole numbers between 31 and 75.
2. Let x = [2 5 1 6].
a.
b.
c.
d.

Add 16 to each element


Add 3 to just the odd-index elements
Compute the square root of each element
Compute the square of each element

3. Let x = [3 2 6 8]' and y = [4 1 3 5]' (NB. x and y should be column


vectors).
a. Add the sum of the elements in x to y
b. Raise each element of x to the power specified by the corresponding
element in y.
c. Divide each element of y by the corresponding element in x
d. Multiply each element in x by the corresponding element in y, calling
the result "z".
e. Add up the elements in z and assign the result to a variable called "w".
f. Compute x'*y - w and interpret the result
4. Evaluate the following MATLAB expressions by hand and use MATLAB to check
the answers
a.
b.
c.
d.
e.
f.
g.
h.

2 / 2 * 3
6 - 2 / 5 + 7 ^ 2 - 1
10 / 2 \ 5 - 3 + 2 * 4
3 ^ 2 / 4
3 ^ 2 ^ 2
2 + round(6 / 9 + 3 * 2) / 2 - 3
2 + floor(6 / 9 + 3 * 2) / 2 - 3
2 + ceil(6 / 9 + 3 * 2) / 2 - 3

5. Create a vector x with the elements :


a.
b.
c.
d.

2, 4, 6, 8, ...
10, 8, 6, 4, 2, 0, -2, -4
1, 1/2, 1/3, 1/4, 1/5, ...
0, 1/2, 2/3, 3/4, 4/5, ...

6. Create a vector x with the elements,


xn = (-1)n+1/(2n-1)
Add up the elements of the version of this vector that has 100 elements
7. Given a vector, t, of length n, write down the MATLAB expressions
that will correctly compute the following:
a. ln(2 + t + t2)

b.
c.
d.
e.
f.

et(1 + cos(3t))
cos2(t) + sin2(t)
tan-1(1) (this is the inverse tangent function)
cot(t)
sec2(t) + cot(t) - 1

Test that your solution works for t = 1:0.2:2


8. Given x = [3 1 5 7 9 2 6], explain what the following commands "mean" by
by summarizing the net result of the command.
a.
b.
c.
d.
e.
f.
g.

x(3)
x(1:7)
x(1:end)
x(1:end-1)
x(6:-2:1)
x([1 6 2 1 1])
sum(x)

9. Given the array A = [ 2 4 1 ; 6 7 2 ; 3 5 9], provide the commands needed


to
a. assign the first row of A to a vector called x1
b. assign the last 2 rows of A to an array called y
c. compute the sum over the columns of A
d. compute the sum over the rows of A
e. compute the standard error of the mean of each column of A (NB. the
standard error of the mean is defined as the standard deviation divided by
the square root of the number of elements used to compute the mean.)
10. Given the arrays x = [1 4 8], y = [2 1 5] and A = [3 1 6 ; 5 2 7],
determine which of the following statements will correctly execute and
provide the result. If the command will not correctly execute, state why it
will not. Using the command whos may be helpful here.
a. x + y
b. x + A
c. x' + y
d. A - [x' y']
e. [x ; y']
f. [x ; y]
g. A - 3
11. Given the array A = [2 7 9 7 ; 3 1 5 6 ; 8 1 2 5], explain the results of
the following commands:
a.
b.
c.
d.
e.
f.
g.
h.
i.
j.
k.

A'
A(:,[1 4])
A([2 3],[3 1])
reshape(A,2,6)
A(:)
flipud(A)
fliplr(A)
[A A(end,:)]
A(1:3,:)
[A ; A(1:2,:)]
sum(A)

l. sum(A')
m. sum(A,2)
k. [ [ A ; sum(A) ] [ sum(A,2) ; sum(A(:)) ] ]
12. Given the array A from problem 4, above, provide the command that will
a.
b.
c.
d.
e.

assign the even-numbered columns of A to an array called B


assign the odd-numbered rows to an array called C
convert A into a 4-by-3 array
compute the reciprocal of each element of A
compute the square-root of each element of A

14. Given that x = [1 5 2 8 9 0 1] and y = [5 2 2 6 0 0 2], execute and


explain the results of the following commands:
a.
b.
c.
d.
e.
f.
g.
h.
i.
j.

x > y
y < x
x == y
x <= y
y >= x
x | y
x & y
x & (~y)
(x > y) | (y < x)
(x > y) & (y < x)

2. The exercises here show the techniques of logical-indexing (indexing with


0-1 vectors). Given x = 1:10 and y = [3 1 5 6 8 2 9 4 7 0], execute and
interpret the results of the following commands:
a.
b.
c.
d.
e.
f.

(x > 3) & (x < 8)


x(x > 5)
y(x <= 4)
x( (x < 2) | (x >= 8) )
y( (x < 2) | (x >= 8) )
x(y < 0)

4. Given x = [3 15 9 12 -1 0 -12 9 6 1], provide the command(s) that will


a.
b.
c.
d.
e.
f.
mean

set the values of x that are positive to zero


set values that are multiples of 3 to 3 (rem will help here)
multiply the values of x that are even by 5
extract the values of x that are greater than 10 into a vector called y
set the values in x that are less than the mean to zero
set the values in x that are above the mean to their difference from the

5. Create the vector x = randperm(35) and then evaluate the following


function using only logical indexing:
y(x) = 2
= x - 4
= 36 - x

if x < 6
if 6 <= x < 20
if 20 <= x <= 35

You can check your answer by plotting y vs. x with symbols. The curve
should be a triangular shape, always above zero and with a maximum of 16.

It

might also be useful to try setting x to 1:35.


simple Mfile) is recommended for this problem.

Using multiple steps (or a

Write brief scripts to evaluate the following functions. If you start each script with a
request for input (using input), you'll be able to test that your code provides the
correct results.
5. h(T) = T - 10
= 0.45 T + 900
Test cases:
6. f(x) = -1
= 0
= 1

when 0 < T < 100


when T > 100

a. T = 5, h = -5
b. T = 110, h = 949.5
if x < 0
if x = 0
if x > 0

Compare your results to the MATLAB function sign.


7.

t(y) =
=
=
=

200
200 + 0.1 (y - 10,000)
1,200 + 0.15 (y - 20,000)
5,700 + 0.25 (y - 50,000)

Test cases:

a. y = 5,000
b. y = 17,000
b. y = 25,000
c. y = 75,000
1. Given the vector x = [1 8 3
will

t
t
t
t
9

=
=
=
=
0

when
when
when
when

y
y
y
y

is
is
is
is

below 10,000
between 10,000 and 20,000
between 20,000 and 50,000
above 50,000

200
900
1,950
11,950
1], create a short set of commands that

a. Add up the values of the elements (Check with sum.)


b. Computes the running sum (for element j, the running sum is the sum of
the elements from 1 to j, inclusive. Check with cumsum.)
c. computes the sine of the given x-values (should be a vector)
2. Create an M-by-N array of random numbers (use rand). Move through the
array, element by element, and set any value that is less than 0.2 to 0 and
any value that is greater than (or equal to) 0.2 to 1.
3. Given x = [4 1 6] and y = [6 2 7], compute the following arrays
a.
b.
c.
d.
e.

aij = xiyj
bij = xi/yj
ci = xiyi, then add up the elements of c.
dij = xi/(2 + xi + yj)
eij = reciprocal of the lesser of xi and yj

4. Write a script that will use the random-number generator rand to determine
the following:
a. The number of random numbers it takes to add up to 20 (or more).
b. The number of random numbers it takes before a number between 0.8 and
0.85 occurs.

c. The number of random numbers it takes before the mean of those numbers
is within 0.01 of 0.5 (the mean of this random-number generator).
It will be worthwhile to run your script several times because you are
dealing
with random numbers. Can you predict any of the results that are
described above?
5. Write a script that asks for a temperature (in degrees Fahrenheit) and
computes the equivalent temperature in degrees Celcius. The script should
keep running until no number is provided to convert. [NB. the function
isempty will be useful here.]
1. Compute the value of pi using the following series

How many terms are needed to obtain an accuracy of 1e-12?


the sum of 100 terms of this series?

How accurate is

2. The Fibonacci numbers are comuted according to the following relation:


Fn = Fn-1 + Fn-2
with F0 = F1 = 1.
a. Compute the first 10 Fibonacci numbers.
b. For the first 50 Fibonacci numbers, compute the ratio

Fn / Fn-1
It is claimed that this ratio approaches the value of the golden mean
( (1 + sqrt(5))/2 ). What do your results show?
3. The Legendre polynomials (Pn(x)) are defined by the following recurrance
relation

(n+1) Pn+1(x) - (2n+1)x Pn(x) + n Pn-1(x) = 0


with P0(x) = 1, P1(x) = x and P2(x) = (3x2 - 1)/2. Compute the next three
Legendre polynomials and plot all 6 over the interval [-1,1].
4. The present value of an annuity (a yearly sum of money) may be computed
from the formula

P = (A/i) [(1 + i)n - 1]/(1 + i)n


where A is the annuity (in $/year), i is the nominal yearly interest rate
(in decimal form), n is the number of years over which the annuity is paid
and P is the present value ($).

Example computation: If i = 0.15 (15%), A = $100/year and n = 10 years


then
P = $501.88.
If you won the $1,000,000 State Lottery and the Lottery offered you the
choice of $500,000 today or $50,000/year for 20 years, which would you take?
You can assume an inflation (interest) rate of 5%.
5. I found the following algorithm on a web page* for computing pi:
1. Set a = 1, b = 1/sqrt(2), t = 1/4 and x = 1
2. Repeat the following commands until the difference between a and b
is within some desired accuracy:
y
a
b
t
x

=
=
=
=
=

a
(a + b)/2
sqrt(b*y)
t - x*(y - a)^2
2*x

3. From the resulting values of a, b and t, an estimate of pi is


Pi_est = ((a + b)^2)/(4*t)
How many repeats are needed to estimate pi to an accuracy of 1e-8? 1e-12?
Compare the performance of this algorithm to the result from Exercise 1,
above.
*http://www.netcom.com/~hjsmith/Pi/Gauss_L.html
6. Write a script that asks for an integer (n) and then computes the
following based on the value of the integer:
While the value of n is greater than 1, replace the integer with
half of its value (n/2) if the integer is even. Otherwise, replace
the integer with three times its value, plus 1 (3*n + 1).
Make provision to count the number of values in (or the length of) the
sequence
that results.
Example calculation: If n = 10, the sequence of integers is 5, 16, 8, 4,
2, 1 and so the length is 6.
Make a plot of the length of the sequence that occurs as a function of the
integers from 2 to 30. For example, when n = 10, the length is 6 while for n
= 15, the length is 17. Is there any pattern? Try larger numbers to see if
any pattern occurs. Is there any integer for which the sequence does
not
terminate?
7. Write a script/function that converts a Roman numeral to its decimal
equivalent. There are two distinct situations that you might design your
program for:
a. The "old" style where the order of the symbols does not matter.
this

In

case, IX and XI both mean 10 + 1 or 11.

You should be able to handle

the
following conversion table:
Roman
I
V
X
L
C
D
M

Decimal
1
5
10
50
100
500
1000

b. The "new" style where the order of the symbols does matter. For
example,
IX is 9 (10 - 1), XC is 90 (100 - 10). The conversion table given
above
still holds and you may assume for this case that the only instances of
"order" you will encounter are
IV (4), IX (9), XL (40), XC (90), CD (400) and CM (900)
The function input will be useful here.

The format

>> str = input('Roman numeral: ','s')


will provide a way to get the Roman number into your program as a string.
It
would be a good idea to try case a. first.
8. Write a function that will do the inverse of the previous problem convert a
decimal number into a Roman number.
9. Compute and plot the path(s) of a set of random walkers which are confined
by
a pair of barriers at +B units and -B units from the origin (where the
walkers
all start from).
A random walk is computed by repeatedly performing the calculation
xj+1 = xj + s
where s is a number drawn from the standard normal distribution (randn in
MATLAB). For example, a walk of N steps would be handled by the code
fragment
x(1) = 0;
for j = 1:N
x(j+1) = x(j) + randn(1,1);
end
There are three possible ways that the walls can "act":
a. Reflecting - In this case, when the new position is outside the walls,
the

walker is "bounced" back by the amount that it exceeded the barrier.


That is,
when xj+1 > B,
xj+1 = B - |B - xj+1|
when xj+1 < (-B),
xj+1 = (-B) + |(-B) - xj+1|
If you plot the paths, you should not see any positions that are beyond
|B|
units from the origin.
b. Absorbing - In this case, if a walker hits or exceeds the wall
positions, it
"dies" or is absorbed and the walk ends. For this case, it is of
interest
to determine the mean lifetime of a walker (i.e., the mean and
distribution
of the number of steps the "average" walker will take before being
absorbed).
c. Partially absorbing - This case is a combination of the previous two
cases.
When a walker encounters a wall, "a coin is flipped" to see if the
walker
relfects or is absorbed. Assuming a probability p (0 < p < 1) for
reflection, the pseudo-code fragment that follows uses the MATLAB
uniform
random-number generator to make the reflect/absorb decision:
if rand < p
reflect
else
absorb
end
What do you do with all the walks that you generate?
of course.
Answering questions like

Compute statistics,

What is the average position of the walkers as a function of time?


What is the standard deviation of the position of the walkers as a
function
of time?
Does the absorbing or reflecting character influence these summaries?
For the absorbing/partial-reflection case, a plot of the number of
surviving
walkers as a function of step numbers is a very interesting thing.
is useful, informative and interesting, particularly if graphically
displayed.
10. The properties of saturated steam are tabulated in many books but that is
not
a useful form for computer use. The following expressions were provided
by

Williamson (Chemical Engineering, May 15, 1972, p. 128):


Saturation temperature, degrees F
Tsat = 8576.65/(15.47538 - ln(Psat)) - 459.216 - 0.023719Psat +
(0.84219e-4)Psat2 - (0.70854e-7)Psat3
Liquid specific volume, ft3/#
Vliq = 0.01655 + (0.150326e-4)Psat - (0.40488e-7)Psat2 +
(0.665584e-10)Psat3 - (0.4053e-13)Psat4
Vapor specific volume, ft3/#
Vvap = 430.8419/(Psat + 1.66) + 0.2031 - (0.000258)Psat
Liquid specific enthalpy, BTU/#
Hliq = 6473.878/(14.01875 - ln(Psat)) - 391.6036 + (0.022915)Psat
Vapor specific enthalpy, BTU/#
Hvap = 1142.342 + (0.76833)Psat - (0.004194)Psat2 + (0.11642e-4)Psat3 (0.157e-7)Psat4 + (0.8086e-11)Psat5
In all cases, the pressure is in psia and the equations are valid for
pressures
between 20 and 600 psia. Maximum error in any computation is below 1%.
a. Create a function that provides these steam properties for a given
vector of
pressures. To save typing, you should be able to copy directly from
the
browser window and paste into the MATLAB editor. Some further
editting
will be required, though.
b. Write a script that allows a user to get different steam properties as
desired. The script should run until the user decides to quit.
c. Extend your script to allow the user to specify the units set (e.g.,
SI,
English, CGS) before requesting numerical values for the properties.
d. Extend the function from a. to provide the heat of vaporization of
water
as a property.
e. What if the user wants to specify the temperature rather than the
pressure?
11. Write a function which computes the cumulative product of the elements in
a
vector. The cumulative product of the jth element of the vector x, xj, is
defined by

pj = (x1)(x2) ... (xj)


for j = 1:length of the vector x.
function:

Create 2 different versions of this

a. One that uses two for-loops to explicitly carry out the calculations,
element by element. An "inner" loop should accumulate the product and
an
"outer" loop should more through the elements of the vector p.
b. One that uses the built-in function prod to replace the inner loop.
In each case, you can check your results with the built-in function,
cumprod.
12. Follow the directions for Exercise 11 but create a function that computes
the
cumulative sum of the elements of a vector. The elements of the
cumulative sum
vector are defined by
sj = x1 + x2 + ... + xj
for j = 1: length of the vector x.
The built-in functions sum and cumsum should be used instead of prod and
cumprod,
respectively.
13. Create a function that generates random arrays of integers beween a and
b,
inclusive. Use the definition line
function A = randint(a,b,M,N)
where a and b define the (inclusive) range and M and N define the size
of the output array (rows and columns, respectively).
a. Test your function with the following piece of code:
x = randint(10,17,100000,1);
hist(x,10:17)
The resulting histogram should be nearly flat from 10 to 17.
particular
attention to the endpoints of the distribution.
b. Test your function with the following pieces of code:
x = randint(-30,5,100000,1);
hist(x,-30:5)
x = randint(-45,-35,100000,1);
hist(x,-45:-35)
x = randint(7,-2,100000,1);
hist(x,-2:7)

Pay

Consider that each of these uses is valid.


c. Modify your code to allow for missing/default inputs. Use the
behavior of
rand to help design your code. You will need to use nargin in your
routine. For example, the function should be able to return
- a 5-by-5 array of integers between 1 and 20: e.g., A =
randint(1,20,5)
- a single random integer between 10 and 50:
e.g., A =
randint(10,50)
- an empty array if not enough inputs are provided.
9. Plot the functions x, x3, ex and ex over the interval 0 < x < 4
2

a. on rectangular paper
b. on semilog paper (logarithm on the y-axis)
c. on log-log paper
Be sure to use an appropriate mesh of x values to get a smooth set
of curves.
10. Make a good plot (i.e., a non-choppy plot) of the function
f(x) = sin(1/x)
for 0.01 < x < 0.1.

How did you create x so that the plot looked good?

11. In polar coordinates (r,t), the equation of an ellipse with one of its
foci at the origin is
r(t) = a(1 - e2)/(1 - (e)cos(t))
where a is the size of the semi-major axis (along the x-axis) and
e is the eccentricity. Plot ellipses using this formula, ensuring
that the curves are smooth by selecting an appropriate number of points
in the angular (t) coordinate. Use the command axis equal to set
the proper axis ratio to see the ellipses.
12. Plot the expression (determined in modelling the growth of the US
population)

P(t) = 197,273,000/(1 + e-0.0313(t - 1913.25))


where t is the date, in years AD, using t = 1790 to 2000.
population is predicted in the year 2020?

What

Вам также может понравиться