CS101 - Lab activity #2

Learning Objectives:

By completing this Lab exercise you should be competent in the following learning objectives:

Instructions:

Study the material in lectures 1 and 2.
Read the instructions below carefully.
Each student should perform the following on an individual basis.
 


Part 1  Matlab constants

A string is a list (vector) of any (keyboard) characters. In Matlab, the keyboard characters are literal constants.

At the Matlab prompt type:

>> last = 'Square Pants'
>> first = 'Sponge Bob'

We can combine string vectors just like we did (in lab 1) numeric valued vectors,

At the Matlab prompt type:

>> name = [ first , last] 

Or, better:

>> name = [first , '  ' , last] 

You can include numeric digits in your string
 

> > movie = [ name, ' Movie 1.23456']


but a character string representation of a number does not correspond to the number,

>> 1 + '1'

Answer question #1 on Lab 2 answer sheet for Part 1.
 

  1. For this question first type the following expression at the Matlab prompt:

>> clear
>> number = 1.2341234

We want to create the string 'test1.2341234'  in Matlab.
Fill in the blank below that creates the string described above. You must include the variable , number in your answer.
(Hint: use the Matlab num2str function. Use Matlab Help or type help num2str to  find  out  how this function works.)

>>  string = [ 'test' ,    _________________________________  ];

Your output should be,

>> string

 test1.2341234


Type the following command and write the output of the "Class" column only.

whos

(variable)                  (Class)


 number           __________________________________________________
 

string               __________________________________________________

Part 2. Matlab Operators

In lab 1 we studied the operators  +   -    *   /   \   ^    and in this lab we will introduce    .*    ./   .\   .^   to complete the set of ten arithmetic operators.
What you need to  know (for the  first midterm)  concerning the ten Matlab arithmetic operators:

Assuming that you have already typed in values for a and b (vectors or matrices)  and (op is one of the ten operators above) then consider the expression,

   >>     a    op     b

We will call  .*  .\  ./  .^ the "dot" operators.
The operators * or .* give the same result when a and b are scalars. In fact the following pairs of operators give the same values when a and b are scalars:
 /   or  ./ 
  \   or  .\
 ^   or  .^

If op is a dot operator then a op b is defined only when the size of a is the same as the size of b. From lab 1, the size of a is m x n where m is the number of rows and n is the number of columns. Use the size function in Matlab to find the size of a variable, for example consider the following row vector a with one row and 3 columns,

>> a = [1 2 3];
>> size(a)


Except for the case when a and b are scalars we will not cover / in CS101.

The  * and \ operators will be covered in a future lab where a and b are not scalars.

Answer questions #2-#13 on Lab 2 answer sheet for Part 2.

To answer the following questions type the following commands at the Matlab prompt:

>> a = 1 : 5 : 15;
>> b = 4:6;

2. Fill in the blanks with the response Matlab gives when you type the following at the Matlab prompt. If the result is an error then write ERROR.
    >>  a
    a  =
                _______________________

3. >> length(a)
    ans =
     
                _______________________

4. >> size(a) , size(b)
    ans  =
 
              _______________________

    ans =

             ________________________

5. >> 2 a
   ans =

            __________________________

6. >> 2 * a
   ans =

            __________________________

7. >> 2 .* a
    ans =


            __________________________

8. >> a * b
   ans =


          ___________________________

9. >> a .* b

    ans =

         ___________________________

10. >>  a .^ 2
    ans =

       _____________________________
11. >> 2 .^ b
   ans =

      ______________________________

12. >>  a ./ b
    ans =

       _____________________________

13. >> a .\ b
    ans =

       ______________________________



Part 3. Vector carving (subscripting)


Given a Matlab vector (for example),

>> x =  .5  + (1:4)
x =
       1.5 2.5 3.5 4.5

we can carve up the vector x using parentheses and an index value from 1 to 4:

>> x(1)
ans =
   1.5

>> x(2)
ans =
   2.5

>> x(4)
ans =
   4.5

We can also carve a vector by specifying a vector of index values:

>> x([ 1 2])
ans =
    1.5 2.5

>> x(1:2)
ans =
    1.5 2.5

>> x([ 2 1])
ans =
    2.5 1.5

>> x([ 4 2])
ans =
    4.5 2.5

>> x(4:-2:2)
ans =
    4.5 2.5

Recall that a:b:c means start at a, increase by b, repeatedly while less than or equal to c. Thus 4:-2:2 is [4 2]

Matlab subscripting works on column vectors in a similar manner. Subscripting on matrices will be covered in a future lab.
Matlab also allows you to use subscripting to change value(s) of a vector.

>> y = [ 1.5 ; 2.5 ; 3.5];

>> y(1) = -1.5
  y =
      -1.5
       2.5
       3.5

>> y( 2:3) = 0
  y =
      -1.5
       0.0
       0.0

Answer questions #14-#20 on Lab 2 answer sheet for Part 3.

Type the following expression at the Matlab prompt then either answer the question or fill in the blanks with the response Matlab returns. If there is an error write ERROR.

>> x = linspace(-2*pi,2*pi,200);
>> y = [ 1 3 5 7 11] ;

14. How many elements does the vector x have?

            ________________________  
15. >> y(3:end)
    ans =

            _______________________
16. >> y(1:end-1)    
      ans =

           ________________________

17. >> x( [1 2])
    ans =
          _________________________(approx.)
18. >> x(1:2)
    ans =
          __________________________(approx.)


19. Fill in the blank below to carve out the  first  three values of y and  prepend zero to these three values. The correct answer would display
      z =
             0  1  3  5

   >> z =     [ 0  , ______________________________ ]
   (The correct answer must use the variable y and subscripting on y)


20. Fill in the blanks below to flip the values of y. The correct answer would display
     flipy =
                11 7 5 3 1

  >> flipy = y(  end : ______  : _______ )
 

Part 4 Matlab functions

The Matlab function rand generates uniformly (equally likely) random numbers between zero and one. The Matlab function floor(x)  rounds the elements of x to the nearest integer less than or equal to x. The Matlab function  ceil(x) rounds the elements of x to the nearest integers greater than or equal to x. For example,

>> floor([1.9   3.4   -4.9   -5.3])
ans =
      1    3     -5    -6

>>ceil([1.9   3.4   -4.9   -5.3] )
ans =
      2    4     -4   -5

In lab 1 we used the Matlab function diff to compute the derivative using symbolic differentiation. However diff also work on vectors (and matrices) by computing consecutive differences, for example,

>> diff( [ 1 2 4 8] )
ans =
        1   2   4
since 2 -1 = 1   ,  4 - 2 = 2 and 8 - 4 = 4.

Answer questions #21-#22 on Lab 2 answer sheet for Part 4.

21. Complete the following Matlab expression to simulate the roll of a single six sided die. Note the possible die values are 1,2,3,4,5, or 6 and are integers.
(Hint: use the function rand with proper scaling)

  >>floor( ____________ * _____________ ) + 1
22. Write a Matlab expression to display random integers(not reals) in the range from 3 to 7 inclusive. (Hint: use the rand and floor function)

  random =     ______________________________________________________________

Part 5 Mathematical functions

A function in mathematics is defined as a set of ordered pairs { (x,y) | x in Domain, y in Range} with the restriction that if (a,b) and (a,c) are in the set then b=c which means that if you plot the set of points in the plane then the plot passes the "vertical line test"- no vertical line cuts the plot in more than one point.
In algebra and calculus classes most functions are represented symbolically, for example the parabola , y = x2 where the Domain is the set of all Real numbers and the Range is the set of all non-negative numbers.
Programs like Mathematica and Matlab can consider functions defined either as a set of ordered pairs or symbolically. Matlab excels at manipulating sets of ordered pairs whereas Mathematica excels at the symbolic representation of functions.


No questions for this Part 5 on the answer sheet.

Part 6  Symbolics in Matlab

The function   y = x2  can be represented in various equivalent forms. Matlab has a built-in function simple  to help simplify complicated symbolic expressions.
For example since sin(x)^2 + cos(x)^2 = 1,

>> syms x
>> simple( x^2 / ( sin(x)^2+cos(x)^2) )
 (after some screen output)

              x^2

The Matlab function factor can be used to factor polynomials.

Answer questions #23-#25 on Lab 2 answer sheet for Part 6.

To answer the following questions, first type,
>> syms x

23. Write the response Matlab returns after typing the following,
     >> factor(x^3 - 1)


    ans = __________________________________________________________

24. Write the response Matlab returns after typing the following, (  i is the "imaginary" number )
       >> simple( exp(i * x) / (cos(x) + i* sin(x) ) )

(Just write the answer, don't write the intermediate results)     ans = ____________________________________   (Euler's formula)

25. Fill in the blank below to simplify the  mathematical function cos(2x) / (cos2(x)-sin2(x)).
   
     >> simple(________________________________________________________________)

Part 7  Discretization in Matlab

A mathematical function y = f(x) can be discretized by sampling (selecting) a finite set of x values for the domain and computing the y values only at these finite x. In Matlab we often choose the values of x to be equally spaced although this is not required. Once a function is discretized we need to know how we can perform the following operations on the discretized function:

      We will do Plotting and Differentiation in this lab and leave the other operations for future labs.

Answer questions #26-#27 on Lab 2 answer sheet for Part 7.

26.  For the function y = x2   choose the sample of x values as [ -1 0 1] type the following command at the Matlab prompt
            >> x = [-1 0 1];
        Fill in the blank below to compute the values for y, (you should type this at the Matlab prompt for use in Part 8)
                   
             >> y = ___________________________________
     That's it, we have now discretized y = x2 .  How good is our discretization? We find out in Part 8.

27. y = sin(x)  Fill in the blanks below to discretize this function. Choose the sample of x values as 50 evenly spaced values from 0 to 2*pi. We will use x2 and y2 so that we can keep these separate from the x and y in problem #26.

        >> x2 = _______________________________
       
        >> y2 = _______________________________

 

Part 8   Plotting

One Matlab command to do plotting is called plot . (see lecture notes 2-7 , 2-8 2-9) If x and y are two vectors of the same length, say for example

>> x = [ 0 1 2]
>> y = [ 3 4 5]
then
>> plot(x,y)
plots the points (0, 3) (1, 4) and (2, 5) in the plane. The function plot by default connects these points with straight lines. We can choose to just plot the data points and not connect the points with lines by typing
>> plot(x,y , '.' )    (that's a period in single quotes)

You can pass just one argument to the Matlab plot function. Type,
>> plot(y)
then use the hold on command so that we can hold (keep) the existing plot while we plot again in the same figure window,
>> hold on
>> plot([1,2,3], y)

Notice that the two plots are identical!

Answer questions #28-#29 on Lab 2 answer sheet for Part 8.

28. Type the following command to plot the discretized parabola we created in Part 7.
>> plot(x,y,'g')   ('g' for green)
Was the discretization in #26 good? Yes, if we wanted to know whether the parabola was concave up or down but No in the sense that the plot doesn't look like a parabola. Fix the problem by plotting y = xusing 100 points from -1 to 1. The plot should be in red, no lines connecting the points and each point should be marked with a *(star) not a . (period).

>> x = ____________________________

>> y = ____________________________

>> plot( _____________ , _____________________, ________________)

29. We will now plot the discretized function from problem #27.
>> plot(y2,x2)

Now put two plots on one figure window, type,
>> hold on
>> plot( x2,y2)
>> grid on
Does plot(x2,y2) give the same results as plot(y2,x2) ________________(YES/NO)?

Part 9  Differentiation

From Calculus, when a function y = f(x) has a tangent line at x = c then its slope is called the derivative. (see graph below)

As an approximation of the derivative at x = c we could choose two points a = x - h/2 and b = x + h/2 where h is a small positive number and compute the slope of the "secant line" (which we can use as an approximation for the slope of the tangent line) as follows:

Slope of secant line (at x = c)
   = rise / run
   = (f(b) - f(a) ) / h
   = (f(x + h/2) - f(x - h/2)) / h   (Centered Difference Formula)

Answer question #30 on Lab 2 answer sheet for Part 9.

Note how we will work with the discretized version of f(x) and not do a symbolic manipulation (differentiation) of the function.

The discretized function y = f(x) is available in vector form:

  x = [x1 , x2 , x3 , ... ,  xn]
y = [y1 , y2 , y3 , ... ,  yn]
where
  y1 = f(x1)
y2 = f(x2)
.
.
.
yn = f(xn)
How can we compute and plot the derivative function y = f'(x)?

If we know only two values of y = f(x), that is x = [x1 , x2] and y = [y1 , y2] then to plot the derivative function f'(x)we can use the Centered Difference Formula

  yprime = (y2 - y1)/(x2 - x1)
   midpoint = (x1 + x2)/2

so that we have approximated the value f'(midpoint) = yprime. Alternatively, we say that the point (midpoint, yprime) lies on the curve of the function of y = f'(x).

  
For three points x = [x1 , x2 , x3] and y = [y1 , y2 , y3] then as above,
  midpoints = [(x1+ x2)/2 , (x2 + x3)/2]  = ( [ x1 , x2] + [ x2 , x3])/2 
yprimes = [(y2 - y1)/(x2 - x1) , (y3 - y2)/(x3 - x2)] = [ (y2 - y1) , (y3 - y2) ] ./ [ (x2 - x1) , (x3 - x2)]

and we can plot these points that lie on the curve of the function y = f'(x)  by typing,

  plot(midpoints,yprimes)
Therefore, given x and y we can compute an approximation of the discretization of the derivative y = f'(x)in Matlab by typing,
 >> midpoints = (x(1:end-1) + x(2:end))/2 ; 
 >> yprimes = diff(y) ./ diff(x) ;

 
  Answer question #31-#32 on Lab 2 answer sheet for Part 9.
 

  Since every real number in  Matlab number takes up eight bytes of memory and there is eight bits per byte, this means that every real number takes up 64 bits. A bit is a 0 or a 1 so there are two possibilities for each bit and thus 264 different possible real numbers can be represented in Matlab. That's not infinite, and since there are an infinite number of real numbers (actually an infinite number between any two real numbers), Matlab has lots of holes or gaps in its representation of the real numbers. This problem is called roundoff error. If you take CS/Math 257 you will learn a lot more about this. But let's do one example.
 
Approximate the derivative of cos(x) at x = pi/2. From Calculus we know the formula for the slope of the derivative
d/dx(cos(x)) = -sin(x)  so plug in x = pi/2 and we get -1.0 exact. Now from the instructions let's use the Centered Difference formula to approximate the derivative, however we will use various values of h, type (or copy and paste)
>> format long e
>> h = 10 .^ -(2:14)
>> derivative = (cos(pi/2 + h/2) - cos(pi/2 - h/2))./h
>> error = abs(derivative + sin(pi/2))
>> clf; %Clear the figure window.
>> loglog(h,error)  % loglog is like plot except it plots the log of both h and error
30. Which value of h gives us the best approximation to the derivative, that is, which value of h gives us the smallest error?

h = _________________________________

Because of roundoff error arbitrarily small values for h won't necessarily give us better values for the derivative or in any numerical calculation( like the definite integral). However, in CS101 we will be in the denial stage and will try to ignore roundoff error. If you can't do this then you are welcome to take a course on Numerical Analysis like CS/Math 257.


Using the formulas derived in Part 9 of the instructions,
 >> midpoints  =  (x(1:end-1) + x(2:end))/2 ; 
 >> yprimes = diff(y) ./ diff(x) ;

fill in the blanks below in order to compute and plot the derivative of y = sin(x) on the interval [0, 2*pi] using 10 equally spaced points.

>> x2 = linspace(0,2*pi,10);
>> y2 = sin(x2);

31.
>> midpoints =  ___________________________________ ;

32.
>> yprimes = __________________________________ ;

>> plot(midpoints, yprimes , 'g')
>> hold on
>> plot(midpoints , cos(midpoints), 'r')        (we know that the derivative of sin(x) is cos(x) so let's compare symbolic vs. discrete)



Part 10  Logical values and relational operators

Logical values are created when you use relational operators such as ( < , <= , > , >= , == , ~=). Matlab treats the value '1' as True and the value '0' as False.
For example, at the Matlab prompt type,



>>   clear

>> x = 5 > 1

>> y = 5 < 1

>> z = 5 == 1 % == means test for equality

>> w = 5 ~= 1 % ~= means test for inequality

>> whos


Note that the "Class" of logical variables is "logical array".
Logical operators can be used with arrays,

>>   x = [5  -1.5  0.0  6.2] > 1

>> y = [5 -1.5 0.0 6.2] < 1

>> z = [5 -1 5 2 5] == 1

>> w = [5 -1 5 2 5] ~= 1

An important use of logical values is doing subscripting. For example, suppose you are given a vector v = [ 1 2 3 4 5 6] and you want to create a vector with only values in v that are >= 3. To do this in Matlab type,

>>   v = 1:6

>> large = v( v >= 3)


  Note that if you manually type

>>   large = v([ 0  0  1  1  1  1])

you will get an error. This seems strange since the values you get from the expression v>=3 are the identical to  [0 0 1 1 1 1] however the Class of each of these expressions is different, the first one being a logical array the latter being double array and Matlab processes these differently when doing subscripting. For example, if you type,

>> v = 1:6 ;

>> test1 = v >=3 ;

>> test2 = [ 0 0 1 1 1 1]

>> whos test1 test2

Name Size Bytes Class

test1 1x6 6 logical array
test2 1x6 48 double array


Answer question #33-#36 on Lab 2 answer sheet for Part 10.

33. Type the following assignment statement at the Matlab prompt,

>>  v = [ -1   0   2   0   3   0   4   0   5   0   6]


Fill in the blank in the Matlab expression below that uses subscripting to extract all non-zero values from v and assign these to the variable w.

>> w =  v ( ___________________________________________)

w =

     -1    2    3    4     5      6


34. Fill in the blank in the Matlab expression below that uses subscripting to extract all zero values from v and assign these to the variable w.

>> w =  v ( ___________________________________________)

w =

     0    0     0     0     0


35.   Suppose that we are given the discretized values of a function y = f(x) as below. We want to find all the roots of the function f . That is, we want to find all the values r such that 0 = f(r).

Type the following assignment statements at the Matlab prompt,
>>  y = [  -1   0    5    0    3    0    4    0    5      0 ] ;
>>  x = [ .1  .2   .3   .4   .5   .6   .7   .8   .9   1.0 ] ;

Fill in the blank in the Matlab expression below that uses subscripting to find all the roots of the discretized function. Yes the answer is [ .2   .4    .6    .8    1.0] but your answer should be a Matlab command that gives you the correct answer no matter what x and y are, assuming of course they have the same number of elements.


r  =    _________________________________________________ ;


  r =
          0.2000   0.4000    0.6000    0.8000    1.0000



36.  For the x and y values from problem #35 find the x values that correspond to the largest value in y. The answer is [ .3   .9]. Write Matlab code to produce this answer. Your answer should work for any values for x and y.  Use subscripting and the Matlab function named max .

result = ______________________________________________ ;

result =
                   0.3000      0.9000

Congratulations, you are done!