Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lecture 2: Programming Basics in MATLAB: September 7

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Lecture 2: Programming basics in MATLAB

September 7
Announcements

Announcements
HW 1 Due next Tuesday in class:
Schedule:
lectures on 9/9 and 9/14 (on 9/14 Simon will replace me).
no lectures on 9/16, 9/21.
back to the usual schedule on 9/23.
Office Hours:
Tomorrow as usual 787 Evans.
On 9/15 and 9/22, Simon will receive you in 1046 Evans.
Useful tips

Interrupting and output


To interrupt an execution of a command in Matlb press
Control-C
Try x1=linspace(0,1,1000000)
Useful tips

Interrupting and output


To interrupt an execution of a command in Matlb press
Control-C
Try x1=linspace(0,1,1000000)
To supress output of an operation add semicolon. Try
x2=linspace(0,1,1000000);.
Newton algorithm

Reminder - Newton algorithm


To find an approximate root(zero point) of a function f , we
setup an iteration procedure

f (xn )
xn+1 = xn − .
f 0 (xn )

we will use that to find 5, i.e. the zero of f (x) = x2 − 5,
therefore, our procedure is

x2n − 5 xn 5
xn+1 = xn − = + .
2xn 2 2xn
In Matlab code

First four iterations of Newton in Matlab


Here how the first four iterations of Newton would look like
x0=2
x1=x0/2+5/(2*x0)
x2=x1/2+5/(2*x1)
x3=x2/2+5/(2*x2)
x4=x3/2+5/(2*x3)
Writing a script

A script
Let’s open the editor window.

We will write the following:


% This script runs four iteration of the Newton algorithm
% to find square root of 5 with starting guess x0=2.
x0=2
x1=x0/2+5/(2*x0)
x2=x1/2+5/(2*x1)
x3=x2/2+5/(2*x2)
x4=x3/2+5/(2*x3)

Save it as, say ’NewtScr.m’ and then write ’NewScr’ in the


command line.
The symbol % comments out the rest of the line.
Scripts

Scripts are good


Can run them over and over, don’t have to retype everything.
Can document what we did using comments.
%USE A LOT OF COMMENTS!
Scripts

Scripts are good


Can run them over and over, don’t have to retype everything.
Can document what we did using comments.
%USE A LOT OF COMMENTS!

Scripts are bad


No flexibility, have to edit the script to change something.
Mess up the workspace.
Functions

Let’s modify our script file


Open the script and add the following line
We need to change our comments, too.
To run it, we write Y=NewtFn in the command line.
Functions

Let’s modify our script file


Open the script and add the following line
We need to change our comments, too.
To run it, we write Y=NewtFn in the command line.

Input
Let’s modify the the first line to function x4=NewtFn2(x0)
and delete x0=2 line.
A good practice is to write end in the last line (more on that
coming)% Save the work, obviously.
To invoke now we write Y=NewtFn2(2).
Now we have a function that accepts the initial guess as an
input.
Functions

Multiple inputs and outputs


To have multiple inputs, we just write function
Output=MyFun(inp1, inp2,.., inpk) and supply k inputs when
invoking the function.
Multiple outputs have the following syntax function [Out1,
Out2]=MyFun(inp1) and then when we invoke we write
[Y1,Y2]=MyFun(x).
’for’ iteration

for
We obviously repeat the same operation. Let’s use the four
loop in order not to type everything again.
Here is the syntax to use ’For’ loop.
for i=1:4
Comands...
end
for starts a new block in our program, which has to be
terminated with end. Lot’s of times we have to nest these
blocks, which is perfectly reasonable. In fact we already
nested the for block in the main block of the function.
Newton with ’for’ loop

Newton with a ’for’ loop


function x=fnNewt3(x0)
xold=x0;
for i=1:4
xnew=xold/2+5/(2*xold);
end
x=xnew; end
Debugging

Debugging
Bugs are programming mistakes in the code. Debugging refers
to correcting programming mistakes.
If you wish to debug a small program, sometimes the easiest
way is just output all the variables.

Serious debugging in Matlab


Let’s debug ’fnNewt3.m’. Open it in the Editor window.
Put a break point on xnew=xold/2+5/(2*xold); line.
Invoke the function in command window. It will stop on the
break point.
Now you have the workspace of the function in front of you.
Use who command to see what variables you have.
Debugging

Using debugger
You can use the buttons in the Editor window.
You also have the following commands:
dbstep to execute one more command in the code.
dbcont to continue to the next break point.
dbquit to stop the execution and quit debuggin.
More flow control

Flaw in fnNewt
There is a flaw in ’fnNewt3.m’.
We can correct it using the ’if’ statement.
First we need to understand how Matlab works with logical
statements and statements.

Boolean expressions
We form boolean expressions from comparison operators
<, >, ==,˜=, <=, >=. There is also a plethora of
is-functions, like isreal.
Such expression will return 0 for if false and 1 if true.
We use the logical operators &&, || and ˜ to form more
complicated expressions.
% Don’t forget to have the parenthesis right.
if, else, elseif
if statement
if condition
expression
end
Executes statement if condition is true.

if..else statement
if condition
expression1
else
expression2
end
Executes statement1 if condition is true, executes statement2 if
condition is false.

More elaborate flow control


Nested if statements.
Newton with input verification

fnNewt5.m
function x=fnNewt5(x0)
if x0==0
fprintf(’Error, input not allowed’)
xnew=nan;
else
xold=x0;
for i=1:4
xnew=xold/2+5/(2*xold);
xold=xnew;
end
end
x=xnew;
end
’while’ loop

while syntax
while condition
expression
end
will repeat expression while the condition holds.
’while’ loop

while syntax
while condition
expression
end
will repeat expression while the condition holds.

while what should really happen


Think how to initialize the variables before you enter the loop.
Before the end of the iteration, think how to advance all the
variables for the next iteration.
For the while loop, make sure that the termination condition
gets updated or you won’t exit the loop.
Exercises

Exercise 1
Rewrite your Newton function to accept as an input the number of
iterations it should perform. What would be a good thing to check
and how would you check it?

Exercise 2
Rewrite your Newton function to run until x2n − 5 ≤ 10−10 .
Additionaly, try to output the number of iterations it took.

More on the next slide


Exercises (continued)
Exercise 3
Design a program that computes n!

Exercise 4
Pn 2.
Design a program that computes k=1 1/k

Exercise 5
The Fibonacci sequence Fn = Fn−1 + Fn−2 for n ≥ 2, where
F0 = 0, F1 = 1, has the explicit formula
√ !n √ !n !
1 1+ 5 1− 5
Fn = √ − .
5 2 2

What could go wrong with programming this in directly?

More on the next slide


Exercises (continued)

Exercise 6
Below is supposed to be a routine to compute the nth term of the
FIbonacci sequence. Use the debugger to find what is wrong with
this program.
————————————————————
function Fn=Fibonnaci(n) Fnminus2=0;
Fnminus1=1;
if (n == 0)||(n == 1)
Fn=n;
else
for i=2:n
Fnminus2=Fnminus1;
Fn=Fnminus1+Fnminus2;
Fnminus1=Fn;
end
end

You might also like