Instructions to MatLab (2)


MatLab can be used as a calculator and a programming language. In this section, we demonstrate the uses of MatLab as a calculator and programming language by an example of finding the fixed point P=0 of g(x)=x2-e-x+1 by fixed-point iterations.

Use MatLab as a Calculator

MatLab can be used as an expression evaluator. To do this you simply type a mathematical expression into the command window. The command window prompt is >>. To enter an expression, type it after the prompt. Press the Return key to execute the command.

Editing in command window
The fixed-point iteration for this problem is: xn+1=g(xn)=xn2-e-xn+1. Start at x0=-1. Compute x1 as follows.
	>> x=-1;  (";" - not to display the value of x on the window)
        >> x=x^2-exp(-x)+1
MatLab responds with
	
           x =
             -0.7183
To compute x2, x3, ..., repeat the previous command by pressing the up arrow key and theReturn key. Here is what you see after repeating twice.
	
        >> x=x^2-exp(-x)+1
           x =
             -0.5350
        >> x=x^2-exp(-x)+1
           x =
             -0.4212

Use MatLab as a programming language

To compute x100, we can use for-loop command as follows.
	
        >> x=-1;
        >> for i=1:100, x=x^2-exp(-x)+1, end
The last value of x displayed on the screen is x100. Use ";" instead of "," after the expression for x if you do not want to have the list of values for xn listed on the screen.
If you want to save the sequence {xn} in an array, modified the previous command as follows.
	
        >> x(1)=-1;
        >> for i=1:100, x(i+1)=x(i)^2-exp(-x(i))+1; end
Note that I use ";" after evaluating x(i+1) this time in order not to display values of x(i+1). If you want to see x50 and x100, type
	
        >> x(51)
           ans =
               -0.0382
        >> x(101)
           ans =
               -0.0195
To compute also the error and the relative error En and Rn, add the formulas after the expression for xn.
	
        >> P=0;
        >> x=-1;
        >> for i=1:100, 
               x=x^2-exp(-x)+1, 
               E=x-P,
               R=E/P,
           end
Or
	
        >> P=0;
        >> x(1)=-1; E(1)=x(1)-P; R(1)=E(1)/P;
        >> for i=1:100, 
               x(i+1)=x(i)^2-exp(-x(i))+1; 
               E(i+1)=x(i+1)-P;
               R(i+1)=E(i+1)/P;
           end
Several commands can be written in one line or multiple lines in the for-loop. They are executed after the command end.
Save the Text of a MatLab Session
diary file_name causes a copy of all subsequent terminal input and most of the resulting output to be written on the named file. diary off suspends it. diary on or diary file_nameturns it back on.