$$ \newcommand{\Oof}[1]{\mathcal{O}(#1)} \newcommand{\F}{\boldsymbol{F}} \newcommand{\J}{\boldsymbol{J}} \newcommand{\x}{\boldsymbol{x}} \renewcommand{\c}{\boldsymbol{c}} $$

 

 

 

Exercises

Exercise 1.1: Error messages

Save a copy of the program ball.m and confirm that the copy runs as the original. You are now supposed to introduce errors in the code, one by one. For each error introduced, save and run the program, and comment how well Matlab's response corresponds to the actual error. When you are finished with one error, re-set the program to correct behavior (and check that it works!) before moving on to the next error.

a) Insert the word hello on the empty line above the assignment to v0.

Solution.

An error message is printed, which at the end states that Error: Undefined function or variable hello The error message tells us explicitly what is wrong.

b) Remove the % sign in front of the comment initial velocity.

Solution.

An error message is printed, which states that

In docli(builtin) at line 1
    In base(base)
    In base()
    In global()
Error: unable to resolve initial to a function call

Matlab gives us the line number where it detected a problem. Matlab "is confused" and tells us that it does not recognize the word initial as the name of a defined function. To a beginner, this may be somewhat misleading, but at least we know the line where the problem is.

c) Remove the = sign in the assignment to v0.

Solution.

An error message is printed, which at the end states that

In docli(builtin) at line 1
    In base(base)
    In base()
    In global()
Error: unable to resolve v0 to a function call

Matlab gives us the line number where it detected a problem. Matlab "is confused" and tells us that it does not recognize the word v0 as the name of a defined function. To a beginner, this may be somewhat misleading, but at least we know the line where the problem is.

d) Change the symbol ^ into **.

Solution.

An error message is printed, stating that

In docli(builtin) at line 5
    In base(base)
    In base()
    In global()
Error: unable to resolve y to a function call

Matlab gives us the line number where it detected a problem. Matlab "is confused" and tells us that it does not recognize the word y as the name of a defined function. To a beginner, this may be somewhat misleading, but at least we know the line where the problem is.

e) Change the calculation of y to y = v0*t.

Solution.

We get no error message this time, even if the calculation of y is wrong! This is because, to Matlab, the "new" way of calculating y is perfectly legal, and Matlab can not know what we wanted to compute. This is therefore another kind of error that sometimes may be hard to find, since we get no error message. To find such errors, answers have to be analyzed quantitatively in some way.

f) Write x on the line just above where y is calculated.

Solution.

An error message is printed, which states that

In docli(builtin) at line 4
    In base(base)
    In base()
    In global()
Error: Undefined function or variable x

Matlab gives us the line number where a problem was detected. Then, it explicitly tells us the problem, namely that x is not defined.

g) Change the statement y = v0*t - 0.5*g*t^2 into y = v0*t - 0.5*g*t^2;. That is, insert a semicolon at the end.

Solution.

We get no answer from the program and no error message. This is correct, since the semi-colon directs Matlab not to print the result to screen. That is no error, but unfortunately we do not see what was computed and stored in y.

Filename: testing_ball.m.

Exercise 1.2: Volume of a cube

Write a program that computes the volume \( V \) of a cube with sides of length \( L = 4 \) cm and prints the result to the screen. Both \( V \) and \( L \) should be defined as separate variables in the program. Run the program and confirm that the correct result is printed.

Hint.

See ball.m in the text.

Solution.

The code reads: The code reads:

L = 4;       % i.e., in cm
V = L^3;
fprintf('The volume is: %g\n', V);

Running the program gives the output

The volume is: 64

Filename: cube_volume.m.

Exercise 1.3: Area and circumference of a circle

Write a program that computes both the circumference \( C \) and the area \( A \) of a circle with radius \( r = 2 \) cm. Let the results be printed to the screen on a single line with an appropriate text. The variables \( C \), \( A \) and \( r \) should all be defined as a separate variables in the program. Run the program and confirm that the correct results are printed.

Solution.

The code reads:

r = 2;
C = 2*pi*r;
A = pi*r**2;

fprintf('Circumference: %g, Area: %g \n', C, A);

Running the program gives the output

Circumference: 12.5664, Area: 12.5664

Filename: circumference_and_area.m.

Exercise 1.4: Volumes of three cubes

We are interested in the volume \( V \) of a cube with length \( L \): \( V=L^3 \), computed for three different values of \( L \).

a) Use the linspace function to compute three values of \( L \), equally spaced on the interval \( [1,3] \).

Solution.

> linspace(1, 3, 3)
ans = 1 2 3

b) Carry out by hand the computation \( V=L^3 \) if \( L \) is an array with three elements. That is, compute \( V \) for each value of \( L \).

Solution.

You should get 1, 8 and 27, which afterwards should compare favorably to output from the code.

c) In a program, write out the result V of V = L.^3 when L is an array with three elements as computed by linspace in a). Compare the resulting volumes with your hand calculations.

Solution.

The code reads:

L = linspace(1, 3, 3);
V = L^3;
fprintf('Volumes: %g, %g, %g\n', V(1), V(2), V(3));

Running the program gives the printout

Volumes: 1 8 27

d) Make a plot of V versus L.

Solution.

The code reads:

plot(L, V);
xlabel('Length of side');
ylabel('Volume');

The plot looks like

Remark. Observe that straight lines are drawn between the three points. To make a smoother cubic curve \( V=L^3 \), we would need to compute more \( L \) and \( V \) values on the curve.

Filename: volume3cubes.m.

Exercise 1.5: Average of integers

Write a program that stores the sum \( 1+2+3+4+5 \) in one variable and then creates another variable with the average of these five numbers. Print the average to the screen and check that the result is correct.

Solution.

The code reads:

sum = 1 + 2 + 3 + 4 + 5;
average = sum/5;
fprintf('average: %g\n', average);

Running the program gives the printout

average =
 3

Filename: average_int.m.

Exercise 1.6: Interactive computing of volume and area

a) Compute the volume in Exercise 1.2: Volume of a cube by using Matlab interactively, i.e., do the computations at the command prompt (in a Matlab shell as we also say). Compare with what you got previously from the written program.

Solution.

> L = 4;
> V = L^3;
> fprintf('The volume is: %g \n', V);
The volume is: 64

b) Do the same also for Exercise 1.3: Area and circumference of a circle.

Solution.

> r = 2;
> C = 2*pi*r;
> A = pi*r^2;
> fprintf('Circumference: %g, Area: %g \n',C,A);
Circumference: 12.5664, Area: 12.5664

Exercise 1.7: Update variable at command prompt

Invoke Matlab interactively and perform the following steps.

  1. Initialize a variable x to 2.
  2. Add 3 to x. Print out the result.
  3. Print out the result of x + 1*2 and (x+1)*2. (Observe how parentheses make a difference).
  4. What variable type is x?

Solution.

> x = 2;
> x = x + 3;
> x + 1*2
ans = 7
> (x + 1)*2
ans = 12

The variable x is an integer throughout the interactive session. The function isinteger may be used to confirm that, see Matlab documentation.

Exercise 1.8: Formatted print to screen

Write a program that defines two variables as x = pi and y = 2. Then let the program compute the product z of these two variables and print the result to the screen as

Multiplying 3.14159 and 2 gives 6.283

Solution.

The code reads:

x = pi;
y = 2;
z = x*y;
fprintf('Multiplying %g and %g gives %g\n', x, y, z);

Running the program gives the requested output.

Filename: formatted_print.m.

Exercise 1.9: Matlab documentation and random numbers

Write a program that prints four random to the screen. The numbers should be drawn from a uniform distribution over the interval \( [0,10) \) (0 inclusive, 10 exclusive). Find the information needed for the task, see for example htpp://www.mathworks.com.

Hint.

Matlab has a built-in function rand for drawing random numbers. Try >> help rand at the command prompt.

Solution.

From Matlab documentation, we find that a function rand will draw random numbers on the open interval between 0 and 1. So, if we multiply these numbers by 10, we get what we need. The code reads:

fprintf('%g\n', rand);
fprintf('%g\n', rand);
fprintf('%g\n', rand);
fprintf('%g\n', rand);

Running the program gives for example (note that numbers change when you run the program again)

0.734546
0.119854
0.203637
0.500444

Filename: drawing_random_numbers.m.