Lab Activity #2 Answer Sheet


Each problem is worth 1/4 point.

Part 1 Matlab constants

  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.

>>  string = [ 'test' ,    ________num2str(number, 8)____  ];   (will accept num2str(number) too )

Your output should be,

>> string

 test1.234

(Hint: use the Matlab num2str function. Use Matlab Help or type help num2str to  find  out  how this function works.)
Type the following command and write the output in the "Class" column only.

whos

(variable)                  (Class)


 number           ____________double array______________________________________
 

string               ____________char array______________________________________



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

>> number = 1.2341234

We want to create the string 'test 1.2341234'  (not 1.2341234) in Matlab.
Fill in the blank below that creates the string described above. You must include the variable , number in your answer.

>>  string = [ 'test ' ,    _____num2str(number,8)____  ];   (9,10,11, ... also work)

(Hint: use the Matlab num2str function. Use Matlab Help or type help num2str to  find  out  how this function works.)


Part 2  Matlab operators

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  =
                ____ 1     6     11    ______

3. >> length(a)
    ans =
     
                ____3_____

4. >> size(a) , size(b)
    ans  =
 
              _____1  3_____

    ans =

             _____1  3_____

5. >> 2 a
   ans =

            _____ERROR_______

6. >> 2 * a
   ans =

            ______2     12    22_____________

7. >> 2 .* a
    ans =


            _____2     12    22____________

8. >> a * b
   ans =


          _________ERROR____________

9. >> a .* b

    ans =

         ____4    30    66______

10. >>  a .^ 2
    ans =

       ___1    36    121_______
11. >> 2 .^ b
   ans =

      ____16     32    64__________

12. >>  a ./ b
    ans =

       ____0.2500    1.1000    1.8333(approx.)__________

13. >> a .\ b
    ans =

       ____4.0000    0.8333(approx.)    0.5455(approx.)__________


Part 3. Vector carving (subscripting)

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?

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

            ____5   7   11_________________
16. >> y(1:end-1)    
      ans =

           _____1   3   5   7___________________

17. >> x( [1 2])
    ans =
          ______-6.2832  6.2200___________________(approx.)
18. >> x(1:2)
    ans =
          ______-6.2832  6.2200__________(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  , _____y(1:3) OR y([1,2,3])_________________________ ]
   (The correct answer must use the variable y and subscriping 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 : ___-1___  : ___1____ )
 

Part 4 Matlab functions

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

  >>floor( _____rand_______ * ______6_______ ) + 1
OR >>floor( _____6_______ * ______rand_______ ) + 1
(Note: The answer key will not always list all the obvious possibilities like this one)

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 =     ________floor( rand * 5) + 3________or floor(rand*5 +3)_____________________________________________

   

Part 6  Symbolics in Matlab


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

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


    _______(x-1)*(x^2+x+1)____________________

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

    _________________1___________________   (Euler's formula)

25. Fill in the blank below to simplify the  mathematical function  cos(2x) / (cos2(x)-sin2(x)). (The domain is a subset of the Reals).
   
     >> simple(__cos(2*x) / (cos(x)^2-sin(x)^2).___________)

Part 7  Discretization in Matlab

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 = ____x.^2 OR x.*x_____________
     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 = _____linspace(0, 2*pi, 50)__________________________
       
        >> y2 = _______sin(x2)________________________

Part 8   Plotting

28. Type the following comand 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 = ___linspace(-1, 1, 100)_________________

>> y = _____x.^2 OR x.*x________

>> plot( ____x________ , _________y___________, _____'r*'_________)

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) ______NO__________(YES/NO)?

Part 9  Differentiation


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 numers. 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,
>> 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))
>> 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 = __________1.0e-5_______________________



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 =  __(x2(1:end-1) + x2(2:end))/2_____________ ;

32.
>> yprimes = _____diff(y2) ./ diff(x2)_______ ;

>> 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 symbolice vs. discrete)



Part 10  Logical values and operators

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 ( ____________v ~=0_______________________________)

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 ( ____________v == 0_____________________________)

w =

     0    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  =    ______________x( y == 0)___________________________________ ;


  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 = _________x( y ==max(y))_____________________________________ ;

result =
                   0.3000      0.9000


Congratulations, you are done!