Third lesson

Contents

Loops

for loop: a sequence of statements which is specified once but which may be carried out several times in succession.

It's structure is : for loop variable (often i) = start : finnish, commands (body of the loop), end

Let's see an example. We wish to create a vector, which elements are 1,2,3, ..., 10^7 with a for loop. We are gong to add one element at the end of the vector in each iteration.

for i=1:1e7
    notthatgood(i)=i;
end
size(notthatgood)
ans =

           1    10000000

With the tic toc command we can measure the time we need to create our vector.

tic % starts the timer
for i=1:1e7
    notthatgoodv(i)=i;
end
toc % displays the time ellapsed since the last tic command
Elapsed time is 1.813470 seconds.

Matlab spends most of the time deleting and copying the notthatgood vector (in each iteration once), since its size changes in each loop. This makes our code inefficient. We can remedy this problem with preallocation (if we know the exact size before we start the loop).

tic
littlebetter=zeros(1,1e7);
for i=1:1e7
    littlebetter(i)=i;
end
toc
Elapsed time is 0.080514 seconds.

However, the best solution is using the : operator.

tic
jobb=1:1e7;
toc
Elapsed time is 0.057109 seconds.

It's strongly recommended during the semester to use : instead of a (for) loop, whenever possible.

While loop

It iterates as long as its condition is true. You have to be careful, it's very easy to create an infite loop, in that case press Ctrl+C to stop the iteration.

Let see an example

i=0;% We have to create the iteration variable (if we need one)
while i<5
    i=i+2;
    fprintf('The value of i=%g\n',i);
end
The value of i=2
The value of i=4
The value of i=6

The for loop's variable doesn't have to be an arithmetic series of integers, it can be any vector (it can even contain floating pont numbers or strings). (it's called a collection-controlled loop).

v=[ 1 6 2.5 9 4 6];
for i=v
    fprintf('The value of i is: %g\n',i)
end
The value of i is: 1
The value of i is: 6
The value of i is: 2.5
The value of i is: 9
The value of i is: 4
The value of i is: 6

This is the reason for the iteration variable of the for and while loop behaves differently. You can't permanetly change the vaule of the loop variable inside a for loop

for i=1:3
    fprintf('The value of i is: %g\n',i)
    i=3;
    fprintf('The value of i is: %g\n',i)
end
The value of i is: 1
The value of i is: 3
The value of i is: 2
The value of i is: 3
The value of i is: 3
The value of i is: 3

Break, continue, return and error

The break command stops the iteration. Fox example let us find the positon of the first zero in a vector!

v=[1 3 2 5 8 0 5 2 7];
i=1;
while v(i)~=0
    i=i+1;
    if i>length(v)
        break
    end

end

if i<=length(v)
    fprintf('The position of the first 0 in the vector is %d\n', i)
else
    fprintf('There is no 0 in the vector.'\n')
end
The position of the first 0 in the vector is 6

When reaching a continue command Matlab skips the remaing commands in the body of the loop, and jumps to the next iteration. In case of nested loops both break and continue affects only the inner loop.

for i=1:3
    for j=1:3
        if i==j
            break
        end
        fprintf('The value of i is: %d, the value of j is: %d\n',i,j);
    end
end
The value of i is: 2, the value of j is: 1
The value of i is: 3, the value of j is: 1
The value of i is: 3, the value of j is: 2

The return command inside of a function interrupts the execution of the function. However, if the values of the output were assinged beforehand, the they are not lost.

We can check the inputs, and in case they are infeaseable we can exit the function with the error command. In this case there will be no outputs at all, even if we assinged them values before.

Guess the output of the following function for inputs 1.5 ,7, 2.5, -1.5!

function out1=strangeexample(in1)

out1=0;

if in1<0
    error('The input is a negative number')
end

if in1>2
    out1=2;
end

return

out1=3;

Oddity of floating point number calculations

Overflow

The default Matlab type for storing floating point numbers is double. It uses 8 bytes, that is 64 bits, and the number are represented in base two.

The (little bit simplified) inner struture of the 8 bytes is the following: The 64 bits is divided into to parts, 53 bit for the mantissa (1 bit for the sign and 52 bits for the digits), 11 bits for the characteristics (1 bits for the sign of the exponent, 10 bits for the exponent). That is we have 52 bits to store the significant digits, and as a consequence:

(2^53+1)-2^53
ans =

     0

The smallest representable positive number is

realmin
ans =

    2.225073858507201e-308

However, we don't have this precision. The precision of the calculactions are the number of the significant digits, which equal to the distance of 1 and the smallest reparesentable number, which is bigger then 1

format long
1+2^-52==1
ans =

  logical

   0

1+2^-53==1
ans =

  logical

   1

In base 10 it's approximatly 15 digits, which is an upper estimete for the precision of our calculations.

Summation

We are going to calculate the sum 1+10*10^(-16) which in theory equals to 10*10^(-16)+1.

s=1;
p=0;
for i=1:10
    s=s+10^(-16);
    p=p+10^(-16);
end
s
s =

     1

p=p+1
p =

   1.000000000000001

The is the floating point summation isn't commutative, it's recommended to add the small terms first.

Substraction

In theorem sqrt(a)-sqrt(a-1) equals to 1/(sqrt(a)+sqrt(a-1)). In practice:

c=sqrt(1e6)-sqrt(1e6-1)
c =

     5.000001250436981e-04

d=1/(sqrt(1e6)+sqrt(1e6-1))
d =

     5.000001250000625e-04

Simplification: loss of digits when subtracting two almost equal quantity. The best practice is to transform the formula before substitution.

Recommended problems

1. problem: Write a function called saddleM, which takes a matrix as an input. The output is a list of positons of the items, which are greater that the sum of their indicies.

For expamle if A=[2 3; 4.5 -1], then the output is: [1 2; 2 1].

2. problem: Write a function called firstL, which takes a vector as an input. The output is the position of the first item of the vector which is grater than 6. If there is no such item, than the output is -1.

3. problem: Write a function called flatV, which takes a vector as an input, say v. The output is a vector, its element are zeros between the first and the ith position, where i is the first position where v(i) is greater then 100. After the ith position the elements of the output are the same as v's.

4.problem: Write a function called reciP, which takes an integer as an input, say n. The output is the smallest integer k for wich the sum $\sum\limits_{i=1}^k \frac{1}{i}$ is greater then n. If more than 10^5 term would be necessary, then the output shall be -1 instead of k.

5. problem: Write a function called secondS, which takes 3 number as an input, a, b and c. They are the coefficionts of the equation ax^2+bx+c=0. The outputs are the two roots of this equation, calculated with the modified solving formula that prevents simplification in case b>>a,c.

6. problem: Write a function called estiLn, which takes a positve number as input, say n. The output is the estime of log(1.5) using the first n terms of the Taylor series, that is

$\ln(1+0.5)=\sum\limits_{k=1}^{\infty} -\frac{(-0.5)^k}{k}$.