Homework excerpted from Prof. Restrepo's 475 hw1

This part of the assignment helps you get familiar with MATLAB.

1.
Log into the system and invoke MATLAB by typing the command matlab. or double click on the MATLAB icon if you are using an NT machine.
2.
At the Matlab prompt >>, type
diary hw1.txt
(Every command should be followed by hitting ``return'' key). The command diary will record your MATLAB session in the file hw1.txt. Now enter
help diary
to receive on-line information about diary. You can get help on any MATLAB command that you are not sure how to use.
3.
Enter
a=[1,2,3]
You get a row vector or $1\times 3$ matrix a. Enter
b=[1;2;3]
You get a column vector or $3\times 1$ matrix b. Notice that rows of a matrix are separated by ``;'' but entries on the same row are separated by ``,'' or blank space. Enter
A = b*a
You get a $3\times 3$ matrix A which is the product (*) of b with a. Enter
S = a*b
You get a single value or a $1\times 1$ matrix S. Note that there is only one data struture in MATLAB, that is, matrix. To calculate the determinant of A, enter
det(A)
Is A invertible?
Now enter
I = [1,0,0; 0,1,0; 0,0,1]
to get a $3\times 3$ identity matrix (or you can get it by simply type I = eye(3), use ``help eye'' to find why). Now enter
B = A + I
and find the determinant of B with
det(B)
Is B invertible? Enter
x = inv(B) * b
to solve the linear system of equations B x = b for vector x. Try also
$ x = B\backslash b$
What is the solution of Bx = b? Does the notation B*a make sense? Why? Enter
B*a and see what happens.
4.
You can put all the commands you entered in the previous subproblem in a file then ask MATLAB to read the file to execute all the commands. This file is called an m-file, which typically stores a sequence of commands and looks like a piece of code. Open another window and in the same directory where you invoked MATLAB, use your favorite editor to write the following in a file called ``test.m'':
          a = [1,2,3];
          b = [1;2;3];
          A = b*a; 
          I = eye(3);
          B = I + A;
          x = B\b
Save the file. In the MATLAB window, type
test
without the .m. It returns x. Note the inclusion of semicolons at the end of statement suppresses the printing of the results. One can also write several statements separated by semicolons on one line.
5.
Enter
help format
Enter
format short
Enter
97.6
Enter
format long
Enter
97.6
Did you see any difference between short and long format? Can you explain? You can add your explanation in the file ``hw1.txt'' after this MATLAB session is over. Find one real number which has the similar phenomena and another one which does not.
6.
MATLAB computes everything using double precision. To find the smallest floating point number $\epsilon$ such that $1+\epsilon \neq 1$, you can run the following sequence of commands (you can put them in a m-file ``epsilon.m'' or input them one by one):
           for i = 1 : 100        % start a "for" loop.
             x = 2^(-i);
             if (1+x) == 1        % logical "if" statement
               y = 2^(-i+1);
               disp( sprintf('EPSILON = %22.18f', y) );
                                  % display "EPSILON with 18 digits after
                                  % the decimal point.
               break;             % exit the loop once "EPSILON" is found.
             end                  % end the "if" statement
           end                    % end the "for" loop.
The words after ``%'' are comments and ignored by MATLAB. Use MATLAB on-line help to find how to use the commands disp, sprintf, break, for, if. Compare the $\epsilon$ that you just obtained with that in Table 2.1. Note that the unit roundoff error is $\epsilon/2$.
In fact, this $\epsilon$ is a MATLAB constant. Enter
eps
What do you get?
7.
In this subproblem, we show you how to plot figures. Several MATLAB graphical commands are very useful. These are plot, subplot, loglog. Use help to find out how they can be used. Let $ f(x) = \sqrt{1+x^2}-1 $ and $ g(x) = \frac{x^2}{\sqrt{1+x^2}+1}. $ It is easy to see these two functions are analytically the same. Use the following m-file to compute f(x), g(x) for $x_k=10^{-k}, k=1,2,\ldots,10$.
           for k = 1 : 10
             x(k) = 10^(-k);
             f(k) = sqrt( 1 + x(k)^2 ) - 1;
             g(k) = ( x(k)^2 ) / ( sqrt( 1 + x(k)^2 ) + 1 );
           end                    
           loglog( x, f, 'o', x, g, '+' )
           print figure.ps          % produce a PostScript file of the figure
Here the sqrt is the square root function. Why $f(x_k) \neq g(x_k)$ epecially for larger k? Why do we choose to use loglog instead of plot to draw the figure? Try to use plot to draw f(xk), g(xk) against xk and see why.
8.
 Use Matlab to create a plot of the function $\cos{(1.7x)}$ for $x\in [0,2\pi]$. Enter

x=0:0.1:2*pi;
y=cos(1.7*x);
plot(x,y)

The first command creates a vector, x, which includes the values 0, 0.1, 0.2, ... up to $2\pi$. The second command creates a vector y of the same length, for which y(i)=cos(1.7x(i)). The last command creates a smooth graph which passes through all the points with coordinates (x(i),y(i)). Hence, this graph only approximates the real graph. The finer spacing we use (say, 0.01 instead of 0.1), the better approximate graph we get.

Create a hard copy of your output. To find out how, enter help printing at the Matlab prompt.

9.
 This exercise will introduce you to one of Matlab's loop structures. Enter the following commands to sum the integers from 1 to 100:
 Sum=0;
 for i=1:100,
    Sum=Sum+i;
 end
 Sum
Create an m-file to do the job (why did we use a capitalized Sum? try help sum).

10.
  For a given A>0 the following sequence converges to the square root of A:

\begin{displaymath}x_0=1 \quad ; \quad x_{n+1}=\frac{1}{2}(x_n + A/x_n) \qquad n\geq 0 ~.\end{displaymath}

Create an m-file which implements that algorithm for the approximate computation of $\sqrt{A}$, by typing the following commands:
 A = input('Enter the number A for which the square root is sought:  ');
 Toll = input('Enter the desired tolerance:  ');
 if A < 0,
    error('A must be nonnegative.')
 elseif Toll <= 0,
    error('Tolerance must be positive.');
 else
    x_old= -Toll;
    x_new=1;
    while abs((x_new-x_old)/x_new) > Toll,
        x_old=x_new;
        x_new=(x_new+A/x_new)/2;
    end
    s1=sprintf('The square root of %8.6f is  %8.6f pm  %8.6f ',A,x_new,Toll);  
    disp(s1)
 end

Use that file in order to compute the approximate square root of A=2, A=16 and A=0 to tolerances .01 and 1e-5.

11.
Enter
diary off
to end saving the session to file ``hw1.txt''. Then enter
quit
to quit MATLAB.
12.
Print the PostScript file ``figure.ps''. Insert your answers to questions in the previous MATLAB session into ``hw1.txt'' and print the file. Hand in the figure and the hardcopy of the file together with the solutions to Part I.



excerpted from Juan Restrepo 475 assignment from 2001-08-23
slightly modified by R. Indik 2008-09-16