Fondamenti di Informatica esempi di funzioni per il ...

Post on 28-Jan-2022

8 views 0 download

Transcript of Fondamenti di Informatica esempi di funzioni per il ...

Fondamenti di Informatica

esempi di funzioni per il calcolo numerico

Emiliano Casalicchio emiliano.casalicchio@uniroma2.it

1

1-2

Solving equations numerically

n  Solving an equation: f (x) = 0 n  As you learned in calculus, the final step in many optimization problems

is to solve an equation of this form where f is the derivative of a function, F , that you want to maximize or minimize.

n  In real engineering problems the function you wish to optimize can come from a large variety of sources, including formulas, solutions of differential equations, experiments, or simulations.

The newton method

Lecture 3

Newton’s Method and Loops

Solving equations numerically

For the next few lectures we will focus on the problem of solving an equation:

f(x) = 0. (3.1)

As you learned in calculus, the final step in many optimization problems is to solve an equation ofthis form where f is the derivative of a function, F , that you want to maximize or minimize. In realengineering problems the function you wish to optimize can come from a large variety of sources,including formulas, solutions of differential equations, experiments, or simulations.

Newton iterations

We will denote an actual solution of equation (3.1) by x∗. There are three methods which you mayhave discussed in Calculus: the bisection method, the secant method and Newton’s method. Allthree depend on beginning close (in some sense) to an actual solution x∗.

Recall Newton’s method. You should know that the basis for Newton’s method is approximation ofa function by it linearization at a point, i.e.

f(x) ≈ f(x0) + f ′(x0)(x− x0). (3.2)

Since we wish to find x so that f(x) = 0, set the left hand side (f(x)) of this approximation equalto 0 and solve for x to obtain:

x ≈ x0 −f(x0)

f ′(x0). (3.3)

We begin the method with the initial guess x0, which we hope is fairly close to x∗. Then we definea sequence of points {x0, x1, x2, x3, . . .} from the formula:

xi+1 = xi −f(xi)

f ′(xi), (3.4)

which comes from (3.3). If f(x) is reasonably well-behaved near x∗ and x0 is close enough to x∗,then it is a fact that the sequence will converge to x∗ and will do it very quickly.

The loop: for ... end

In order to do Newton’s method, we need to repeat the calculation in (3.4) a number of times. Thisis accomplished in a program using a loop, which means a section of a program which is repeated.

8

3

How it works?

n  x1 = x0 - f(x0)/f1(x0) n  x2 = x1 - f(x1)/f1(x1)n  x3 = x2 - f(x2)/f1(x2)n  …n  Until ????

■ We don’t know in advance how many xi must be computed

■ A possibility is to fix N and compute xi for 1<=i<=N

4

The matlab solution

function x = mynewton(f,f1,x0,n) % Solves f(x) = 0 by doing n steps of Newton’s method starting at x0. % Inputs: f -- the function, input as an inline % f1 -- it’s derivative, input as an inline % x0 -- starting guess, a number % n -- the number of steps to do % Output: x -- the approximate solution format long % prints more digits format compact % makes the output more compact x = x0; % set x equal to the initial guess x0 for i = 1:n % Do n times

x = x - f(x)/f1(x) % Newton’s formula, prints x too end 5

It is correct or there is an error?

Type “help format” on the command windows

x=x0

i=1 x=x0-f(x0)/f1(x0)

i=2 x=[x0+f(x0)/f1(x0)]-f(x0+f(x0)/f1(x0))/f1(x0+f(x0)/f1(x0))

i=3 ....

6

Try it

n  In the command window define an inline function: f (x) = x^3 − 5 > f = inline(‘x^3 - 5’) n  and define f1 to be its derivative, i.e. > f1 = inline(‘3*x^2’). n  Then run mynewton on this function.

■  By trial and error, what is the lowest value of n for which the program converges (stops changing)?

■  By simple algebra, the true root of this function is 5^(1/3). How close is the program’s answer to the true value?

7

How can we modify the code to store the result?

function x = mynewton(f,f1,x0,n) % Solves f(x) = 0 by doing n steps of Newton’s method starting at x0. % Inputs: f -- the function, input as an inline % f1 -- it’s derivative, input as an inline % x0 -- starting guess, a number % n -- the number of steps to do % Output: x -- the approximate solution format long % prints more digits format compact % makes the output more compact x(1) = x0; % set x equal to the initial guess x0 for i = 1:n-1 % Do n times

x(i+1)= x(i) - f(x(i))/f1(x(i)) % Newton’s formula,

% prints x too end

8

Controlling Error

n  If we are trying to find a numerical solution of an equation f (x) = 0, then there are a few different ways we can measure the error of our approximation. The most direct way to measure the error would be as:

n  where xn is the n-th approximation and x∗ is the true value. However, we usually do not know the value of x∗, or we wouldn’t be trying to approximate it. This makes it impossible to know the error directly, and so we must be more clever

n 

9

Lecture 4

Controlling Error and ConditionalStatements

Measuring error

If we are trying to find a numerical solution of an equation f(x) = 0, then there are a few differentways we can measure the error of our approximation. The most direct way to measure the errorwould be as:

{Error at step n} = en = xn − x∗

where xn is the n-th approximation and x∗ is the true value. However, we usually do not know thevalue of x∗, or we wouldn’t be trying to approximate it. This makes it impossible to know the errordirectly, and so we must be more clever.

For Newton’s method we have the following principle: At each step the number of significantdigits roughly doubles. While this is an important statement about the error (since it meansNewton’s method converges really quickly), it is somewhat hard to use in a program.

Rather than measure how close xn is to x∗, in this and many other situations it is much morepractical to measure how close the equation is to being satisfied, in other words, how close f(xn)is to 0. We will use the quantity rn = f(xn) − 0, called the residual, in many different situations.Most of the time we only care about the size of rn, so we look at |rn| = |f(xn)|.

The if ... end statement

If we have a certain tolerance for |rn| = |f(xn)|, then we can incorporate that into our Newtonmethod program using an if ... end statement:

11

Controlling Error

n  Rather than measure how close xn is to x∗ , in this and many other situations it is much more practical to measure how close the equation is to being satisfied, in other words, how close f(xn) is to 0.

n  We will use the quantity

■  rn = f(xn) − 0, called the residual

n  Most of the time we only care about the size of r, so we look at

■  |rn| = |f(xn) |

10

The Matlab solution (for loop)

function x = mynewton(f,f1,x0,n,tol) % Solves f(x) = 0 by doing n steps of Newton’s method starting at x0. % Inputs: f -- the function, input as an inline % f1 -- it’s derivative, input as an inline % x0 -- starting guess, a number % tol -- desired tolerance, prints a warning if |f(x)|>tol % Output: x -- the approximate solution x = x0; % set x equal to the initial guess x0 for i = 1:n % Do n times

x = x - f(x)/f1(x); % Newton’s formula end r = abs(f(x)); if r > tol

warning(’The desired accuracy was not attained’) end

11

Type “help warning” on the command windows

The Matlab solution (while loop)

function x = mynewtontol(f,f1,x0,tol) % Solves f(x) = 0 by doing Newton’s method starting at x0. % Inputs: f -- the function, input as an inline % f1 -- it’s derivative, input as an inline % x0 -- starting guess, a number % tol -- desired tolerance, goes until |f(x)|<tol % Output: x -- the approximate solution x = x0; % set x equal to the initial guess x0 y = f(x); while abs(y) > tol % Do until the tolerence is reached.

x = x - y/f1(x); % Newton’s formula y = f(x);

end

12

We have a big problem here…this implementation could be dangerouse

The Matlab solution (while loop) function x = mynewtontol(f,f1,x0,tol,max_iter) % …

x = x0; % set x equal to the initial guess x0 y = f(x); i=0;while abs(y) > tol && i=i+1 <= max_iter % Do until the tolerance is reached or the max number of

% iteration is reached. x = x - y/f1(x); % Newton’s formula y = f(x);

end if abs(y) > tol

warning(’The desired accuracy was not attained’) end

13

Warning, error, printf

n  Why tracking the behavior of your algorithm?

■  to check the behavior conforms with your requirements

■  to verify the behavior is semantically correct n  Type

■ help warning ■ help error

14

We will have a class dedicated to

DEBUGGING

More methods

■ Bisection method ■ Locating roots ■ Secant methods

15

Bisection method

n  Suppose that c = f (a) < 0 and d = f (b) > 0. n  If f is continuous, then obviously it must be zero at some x∗ between a and b.

The bisection method then consists of looking half way between a and b for the zero of f , i.e. let x = (a + b)/2 and evaluate y = f (x).

n  Unless this is zero, then from the signs of c, d and y we can decide which new interval to subdivide. In particular, ■  if c and y have the same sign, then [x, b] should be the new interval,

but ■  if c and y have different signs, then [a, x] should be the new interval.

16

Lecture 5

The Bisection Method and LocatingRoots

Bisecting and the if ... else ... end statement

Recall the bisection method. Suppose that c = f(a) < 0 and d = f(b) > 0. If f is continuous,then obviously it must be zero at some x∗ between a and b. The bisection method then consists oflooking half way between a and b for the zero of f , i.e. let x = (a + b)/2 and evaluate y = f(x).Unless this is zero, then from the signs of c, d and y we can decide which new interval to subdivide.In particular, if c and y have the same sign, then [x, b] should be the new interval, but if c and yhave different signs, then [a, x] should be the new interval. (See Figure 5.1.)

Deciding to do different things in different situations in a program is called flow control. Themost common way to do this is the if ... else ... end statement which is an extension of theif ... end statement we have used already.

Bounding the Error

One good thing about the bisection method, that we don’t have with Newton’s method, is that wealways know that the actual solution x∗ is inside the current interval [a, b], since f(a) and f(b) havedifferent signs. This allows us to be sure about what the maximum error can be. Precisely, theerror is always less than half of the length of the current interval [a, b], i.e.

{Absolute Error} = |x− x∗| < (b− a)/2,

where x is the center point between the current a and b.

x0x1 x2a0 b0

a1 b1

a2 b2✉

Figure 5.1: The bisection method.

14

Bounding the error

n  One good thing about the bisection method, that we don’t have with Newton’s method, is that we always know that the actual solution x∗ is inside the current interval [a, b], since f (a) and f (b) have different signs.

n  This allows us to be sure about what the maximum error can be. Precisely, the error is always less than half of the length of the current interval [a, b], i.e.

■  {Absolute Error} = |x − x∗ | < (b − a)/2, n  where x is the center point between the current a and b.

17

The algorithm

18

c=f(a); d=f(b)

a,b,n,f

c*d>0.0 f(x)>0 (or <0) for all x in [a,b]

x=(b-a)/2; y=f(x)

Y=0.0 e=0; exit

c*Y<0.0 a=x b=x

n>0.0 e=(b-a)/2; exit

YES

n=n-1

NO NO

NO

YES

YES

YES

Lecture 5

The Bisection Method and LocatingRoots

Bisecting and the if ... else ... end statement

Recall the bisection method. Suppose that c = f(a) < 0 and d = f(b) > 0. If f is continuous,then obviously it must be zero at some x∗ between a and b. The bisection method then consists oflooking half way between a and b for the zero of f , i.e. let x = (a + b)/2 and evaluate y = f(x).Unless this is zero, then from the signs of c, d and y we can decide which new interval to subdivide.In particular, if c and y have the same sign, then [x, b] should be the new interval, but if c and yhave different signs, then [a, x] should be the new interval. (See Figure 5.1.)

Deciding to do different things in different situations in a program is called flow control. Themost common way to do this is the if ... else ... end statement which is an extension of theif ... end statement we have used already.

Bounding the Error

One good thing about the bisection method, that we don’t have with Newton’s method, is that wealways know that the actual solution x∗ is inside the current interval [a, b], since f(a) and f(b) havedifferent signs. This allows us to be sure about what the maximum error can be. Precisely, theerror is always less than half of the length of the current interval [a, b], i.e.

{Absolute Error} = |x− x∗| < (b− a)/2,

where x is the center point between the current a and b.

x0x1 x2a0 b0

a1 b1

a2 b2✉

Figure 5.1: The bisection method.

14

19

function [x e] = mybisect(f,a,b,n) % function [x e] = mybisect(f,a,b,n) % Does n iterations of the bisection method for a function f % Inputs: f -- an inline function % a,b -- left and right edges of the interval % n -- the number of bisections to do. % Outputs: x -- the estimated solution of f(x) = 0 % e -- an upper bound on the error format long c = f(a); d = f(b); if c*d > 0.0

error(‘Function has same sign at both endpoints.’) end disp(‘ x y’);for i = 1:n

x = (a + b)/2; y = f(x); disp([ x y]) if y == 0.0 % solved the equation exactly

e = 0; break % jumps out of the for loop

end if c*y < 0

b=x; else

a=x; end

end e = (b-a)/2;

Homework

n  Modify mybisect to solve until the error is bounded by a given tolerance. n  How should error be measured? n  Run your program on the function f (x) = 2x3 +3x −1 with starting

interval [0, 1] and a tolerance of 10−8 . How many steps does the program use to achieve this tolerance?

20

n  Let us define f(x) as a “permanent” function rather then “inline”

function y=f(x)

y= 3*x.^2+2*x.^3+12;

>> plot(f(-100:1:100));

>> plot(-100:1:100,f(-100:1:100));

Root finder (graphical method!!!) Use

21 -100

0

By default the x axis range from 0 to number of f points How to specify a

different range for x axis

TIP

>> mybisect(f,-100,100,40)??? Attempted to access f(-100); index must be a positive integeror logical.

Error in ==> mybisect at 10c = f(a); d = f(b);

22

NON POSSO USARE UNA FUNZIONE “PERMANENTE” COME INPUT DI UNA FUNZIONE DEVO USARE UN “OGGETTO INLINE”

>> f=inline('3*x.^2+2*x.^3+12');>> [x e]=mybisect(f,-20,20,10)…

x = -2.460937500000000e = 0.019531250000000

23

Locating a Root

n  The bisection method and Newton’s method are both used to obtain closer and closer approximations of a solution, but both require starting places. The bisection method requires two points a and b that have a root between them, and Newton’s method requires one point x0 which is reasonably close to a root.

n  How do you come up with these starting points? It depends.

■  If you are solving an equation once, then the best thing to do first is to just graph it.

■  If you have to solve the same equation many times, but with different coefficients the first thing you want to take advantage of is the natural domain of the problem, i.e. on what interval is a solution physically reasonable.

24

The algorithm function [a,b] = myrootfind(f,a0,b0) % function [a,b] = myrootfind(f,a0,b0) % Looks for subintervals where the function changes sign % Inputs: f -- an inline function % a0 -- the left edge of the domain % b0 -- the right edge of the domain % Outputs: a -- an array, giving the left edges of subintervals % on which f changes sign % b -- an array, giving the right edges of the subintervals n = 1001; % number of test points to use a = []; % start empty array b = []; x = linspace(a0,b0,n); y = f(x); for i = 1:(n-1)

if y(i)*y(i+1) < 0 % The sign changed, record it a = [a x(i)]; b = [b x(i+1)]; end

end if a == []

warning('no roots were found') end

25

>> f=inline('3*x.^2+2*x.^3+12'); >> [a,b]=myrootfind(f,-100,100) a = -2.599999999999994 b = -2.400000000000006

Secant method

n  The secant method requires two initial points x0 and x1 which are both reasonably close to the solution x∗ . Preferably the signs of y0 = f (x0 ) and y1 = f (x1 ) should be different.

n  Once x0 and x1 are determined the method proceeds by the following formula:

26

Lecture 6

Secant Methods*

In this lecture we introduce two additional methods to find numerical solutions of the equationf(x) = 0. Both of these methods are based on approximating the function by secant lines just asNewton’s method was based on approximating the function by tangent lines.

The Secant Method

The secant method requires two initial points x0 and x1 which are both reasonably close to thesolution x∗. Preferably the signs of y0 = f(x0) and y1 = f(x1) should be different. Once x0 and x1

are determined the method proceeds by the following formula:

xi+1 = xi −xi − xi−1

yi − yi−1yi (6.1)

Example: Suppose f(x) = x4 − 5 for which the true solution is x∗ = 4√5. Plotting this function

reveals that the solution is at about 1.25. If we let x0 = 1 and x1 = 2 then we know that the rootis in between x0 and x1. Next we have that y0 = f(1) = −4 and y1 = f(2) = 11. We may thencalculate x2 from the formula (6.1):

x2 = 2−2− 1

11− (−4)11 =

19

15≈ 1.2666....

Pluggin x2 = 19/15 into f(x) we obtain y2 = f(19/15) ≈ −2.425758.... In the next step we woulduse x1 = 2 and x2 = 19/15 in the formula (6.1) to find x3 and so on.

Below is a program for the secant method. Notice that it requires two input guesses x0 and x1, butit does not require the derivative to be input.

figure yet to be drawn, alas

Figure 6.1: The secant method.

17

The algorithm

n  Homework:

■ Write down the flow chart diagram and the matlab code

27

The matlab code

function x = mysecant(f,x0,x1,n) format long % prints more digits format compact % makes the output more compact % Solves f(x) = 0 by doing n steps of the secant method starting with x0 and x1. % Inputs: f -- the function, input as an inline function % x0 -- starting guess, a number % x1 -- second starting geuss % n -- the number of steps to do % Output: x -- the approximate solution y0 = f(x0); y1 = f(x1); for i = 1:n % Do n times x = x1 - (x1-x0)*y1/(y1-y0) % secant formula. y=f(x) % y value at the new approximate solution. % Move numbers to get ready for the next step x0=x1; y0=y1; x1=x; y1=y; end 28

Homework

n  Modify mysecant to solve until the error is bounded by a given tolerance.

n  How should error be measured?

29

The Regula Falsi Method

n  The Regula Falsi method is somewhat a combination of the secant method and bisection method.

n  The idea is to use secant lines to approximate f (x), but choose how to update using the sign of f (xn).

n  Just as in the bisection method, we begin with a and b for which f (a) and f (b) have different signs.

n  Then let:

n  Next check the sign of f (x). If it is the same as the sign of f (a) then x becomes the new a. Otherwise let b = x.

30

18 LECTURE 6. SECANT METHODS*

function x = mysecant(f,x0,x1,n)format long % prints more digitsformat compact % makes the output more compact% Solves f(x) = 0 by doing n steps of the secant method starting with x0 and x1.% Inputs: f -- the function, input as an inline function% x0 -- starting guess, a number% x1 -- second starting geuss% n -- the number of steps to do% Output: x -- the approximate solutiony0 = f(x0);y1 = f(x1);for i = 1:n % Do n times

x = x1 - (x1-x0)*y1/(y1-y0) % secant formula.y=f(x) % y value at the new approximate solution.

% Move numbers to get ready for the next stepx0=x1;y0=y1;x1=x;y1=y;

end

The Regula Falsi Method

The Regula Falsi method is somewhat a combination of the secant method and bisection method.The idea is to use secant lines to approximate f(x), but choose how to update using the sign off(xn).

Just as in the bisection method, we begin with a and b for which f(a) and f(b) have different signs.Then let:

x = b−b− a

f(b)− f(a)f(b).

Next check the sign of f(x). If it is the same as the sign of f(a) then x becomes the new a. Otherwiselet b = x.

Convergence

If we can begin with a good choice x0, then Newton’s method will converge to x∗ rapidly. The secantmethod is a little slower than Newton’s method and the Regula Falsi method is slightly slower thanthat. Both however are still much faster than the bisection method.

If we do not have a good starting point or interval, then the secant method, just like Newton’smethod can fail altogether. The Regula Falsi method, just like the bisection method always worksbecause it keeps the solution inside a definite interval.

Simulations and Experiments

Although Newton’s method converges faster than any other method, there are contexts when itis not convenient, or even impossible. One obvious situation is when it is difficult to calculate a

Homework

n  Realize a program that implement the Regula Falsi Method. n  Modify the algorithm to solve until the error is bounded by a given

tolerance. n  How should error be measured?

31

Integration

32

Lecture 21

Integration: Left, Right and TrapezoidRules

The Left and Right endpoint rules

In this section, we wish to approximate a definite integral:∫ b

af(x) dx

where f(x) is a continuous function. In calculus we learned that integrals are (signed) areas and canbe approximated by sums of smaller areas, such as the areas of rectangles. We begin by choosingpoints {xi} that subdivide [a, b]:

a = x0 < x1 < . . . < xn−1 < xn = b.

The subintervals [xi−1, xi] determine the width ∆xi of each of the approximating rectangles. Forthe height, we learned that we can choose any height of the function f(x∗

i ) where x∗i ∈ [xi−1, xi].

The resulting approximation is:∫ b

af(x) dx ≈

n∑

i=1

f(x∗i )∆xi.

To use this to approximate integrals with actual numbers, we need to have a specific x∗i in each

interval. The two simplest (and worst) ways to choose x∗i are as the left-hand point or the right-hand

point of each interval. This gives concrete approximations which we denote by Ln and Rn given by

Ln =n∑

i=1

f(xi−1)∆xi and

Rn =n∑

i=1

f(xi)∆xi .

function L = myleftsum(x,y)% produces the left sum from data input.% Inputs: x -- vector of the x coordinates of the partition% y -- vector of the corresponding y coordinates% Output: returns the approximate integraln = max(size(x)); % safe for column or row vectorsL = 0;for i = 1:n-1

L = L + y(i)*(x(i+1) - x(i));end

75

The matlab code

function L = myleftsum(x,y) % produces the left sum from data input. % Inputs: x -- vector of the x coordinates of the partition % y -- vector of the corresponding y coordinates % Output: returns the approximate integral n = max(size(x)); % safe for column or row vectors L = 0; for i = 1:n-1 L = L + y(i)*(x(i+1) - x(i)); end

33 Given f(x) how can I obtain x and y

function y=f(x)y= 3*x.^2+2*x.^3+12; >> x=0:1:100 >> y=f(x) >> L = myleftsum(x,y)

34

Invocation of function in a function

function z = integralApproximation(f,a,b,n,int_max) for i=1:n x=a:floor(int_max/i):b; y=f(x); z(i) = myleftsum(x,y);end integralApproximation(f,0,100,10,20) ans = Columns 1 through 5 32721200 41356200 38129472 46052450 47022000 Columns 6 through 10 46090836 48991400 48991400 48991400 48991400

35

Instead of two separated functions you can have two functions in the same .m file

36

Useful for “service functions”

Homeworks

n  evaluate the difference in using

■  round and ceil instead of floor n  Plot the three z vectors

37

Cumulative sum of a vector: problem definition

38

n  If x is a vector with N elements denoted x(n), n=1,2,...,N, n  cumulative sum ok degree k is defined as

n  design and implement the function cumulativeSum(x) defined as

y(k) = x(i)i=1

k

cumulativeSum(x) = (y(1), y(2),..., y(N ))

Cumulative sum of a vector: how to solve the problem

n  y(1)=x(1) n  y(2)=x(1)+x(2) n  y(k)=x(1)+x(2)+…+x(k)

n  How can I compute y(k)?

■ using a loop from 1 to k and ■ at each step y(k)=y(k)+x(i)

n  How can I compute comulativeSum(x)?

■ using a loop from 1 to length of x and ■ at each step, computing y(k)

n  Summarizing

■  I need two nested loops

39

Cumulative sum of a vector: the code

function s = cumulativeSum(x)% s = cumulativeSum(x)% This function compute the cumulative sum of a vector x% s is a vector such that s(i) contains the sum of the first i elements of x %n=length(x);s=zeros(1,n);for i=1:n for j=1:i s(i)=s(i)+x(j) endend

40

Cumulative sum of a vector: execution

>> x=[1 5 7]x = 1 5 7>> y=cumulativeSum(x)s = 1 0 0s = 1 1 0s = 1 6 0s = 1 6 1s = 1 6 6s = 1 6 13y = 1 6 13

41

Step1.1

Step2.1

Step2.2

Step3.1

Step3.2

Step3.3

Cumulative (column) sum of a matrix: problem statement

42

• The product y is the scalar

y =N∏

n=1

x(n) = x(1) · x(2) · · ·x(N)

• The cumulative sum y is the vector having elements y(k), k = 1, 2, . . . , N

y(k) =k

n=1

x(n) = x(1) + x(2) + · · · + x(k)

• The cumulative product y is the vector having elements y(k), k = 1, 2, . . . , N

y(k) =k

n=1

x(n) = x(1) · x(2) · · ·x(k)

If X is a matrix with M rows and N columns with elements denoted x(m, n), m = 1, 2, . . . , M, n =1, 2, . . . , N , then

• The column sum y is the vector having elements y(n), n = 1, 2, . . . , N

y(n) =M∑

m=1

x(m, n) = x(1, n) + x(2, n) + · · · + x(M, n)

• The column product y is the vector having elements y(n), n = 1, 2, . . . , N

y(n) =M∏

m=1

x(m, n) = x(1, n) · x(2, n) · · ·x(M, n)

• The cumulative column sum Y is the matrix with M rows and N columns with elementsdenoted y(k, n), k = 1, 2, . . . , M, n = 1, 2, . . . , N

y(k, n) =k

m=1

x(m, n) = x(1, n) + x(2, n) + · · · + x(k, n)

• The cumulative column product Y is the matrix with M rows and N columns withelements denoted y(k, n), k = 1, 2, . . . , M, n = 1, 2, . . . , N

y(k, n) =k

m=1

x(m, n) = x(1, n) · x(2, n) · · ·x(k, n)

The Matlab functions implementing these mathematical functions are the following.

141

• The product y is the scalar

y =N∏

n=1

x(n) = x(1) · x(2) · · ·x(N)

• The cumulative sum y is the vector having elements y(k), k = 1, 2, . . . , N

y(k) =k

n=1

x(n) = x(1) + x(2) + · · · + x(k)

• The cumulative product y is the vector having elements y(k), k = 1, 2, . . . , N

y(k) =k

n=1

x(n) = x(1) · x(2) · · ·x(k)

If X is a matrix with M rows and N columns with elements denoted x(m, n), m = 1, 2, . . . , M, n =1, 2, . . . , N , then

• The column sum y is the vector having elements y(n), n = 1, 2, . . . , N

y(n) =M∑

m=1

x(m, n) = x(1, n) + x(2, n) + · · · + x(M, n)

• The column product y is the vector having elements y(n), n = 1, 2, . . . , N

y(n) =M∏

m=1

x(m, n) = x(1, n) · x(2, n) · · ·x(M, n)

• The cumulative column sum Y is the matrix with M rows and N columns with elementsdenoted y(k, n), k = 1, 2, . . . , M, n = 1, 2, . . . , N

y(k, n) =k

m=1

x(m, n) = x(1, n) + x(2, n) + · · · + x(k, n)

• The cumulative column product Y is the matrix with M rows and N columns withelements denoted y(k, n), k = 1, 2, . . . , M, n = 1, 2, . . . , N

y(k, n) =k

m=1

x(m, n) = x(1, n) · x(2, n) · · ·x(k, n)

The Matlab functions implementing these mathematical functions are the following.

141

Cumulative (column) sum of a matrix: problem solution

n  How can I solve the problem

■ Each column is a vector ■ The resulting matrix is composed by the

cumulative sum vector of each column ■ We can use what we have done before with

comulativeSum(x)

43

Cumulative (column) sum of a matrix: the code

function s = cumulativeSumM(x)% s = cumulativeSum(x)% This function compute the cumulative column sum of a matrix x% %n=size(x,1);m=size(x,2);s=zeros(n,m);for k=1:m for i=1:n for j=1:i s(i,k)=s(i,k)+x(j,k) end endend 44

Cumulative (column) sum of a matrix: execution

>> xx = 1 4 5 2 5 7>> cumulativeSumM(x)s = 1 0 0 0 0 0s = 1 0 0 1 0 0s = 1 0 0 3 0 0s = 1 4 0 3 0 0s = 1 4 0 3 4 0

45

s = 1 4 0 3 9 0s = 1 4 5 3 9 0s = 1 4 5 3 9 5s = 1 4 5 3 9 12ans = 1 4 5 3 9 12

Step1

Step1

Step1

Step2

Step2

Step2

Step3

Step3

Step3

Improving the solution

n  We can improve the solution using the functional programming paradigm and avoiding rewrite code for cumulativeSum

function s = cumulativeSumM(x)% s = cumulativeSum(x)% This function compute the cumulative column sum of a matrix x% %n=size(x,1);

m=size(x,2);s=zeros(n,m);for k=1:m s(:,k)=cumulativeSum(x(:,k))';end

46

Homework

n  Cumulative product of vector and matrix elements

47

Running the script:

Minimum cost (dollars):9.1394e+004

Radius R for minimum cost (m):4.9240

Height H for minimum cost (m):3.2816

Note that the radius corresponding to minimum cost (Rmin = 4.9240 is close to the approximatevalue, Rest = 4.5708 that we computed to assist in the selection of a range of R to investigate.The plot of cost C versus radius R is shown in Figure 7.3.

3 3.5 4 4.5 5 5.5 6 6.5 70.9

0.95

1

1.05

1.1

1.15x 105 Tank Design

Radius R, m

Cos

t C, D

olla

rs

Figure 7.3: Tank design problem: cost versus radius

7.2 Sums and Products

If x is a vector with N elements denoted x(n), n = 1, 2, . . . , N , then:

• The sum y is the scalar

y =N

n=1

x(n) = x(1) + x(2) + · · · + x(N)

140

• The product y is the scalar

y =N∏

n=1

x(n) = x(1) · x(2) · · ·x(N)

• The cumulative sum y is the vector having elements y(k), k = 1, 2, . . . , N

y(k) =k

n=1

x(n) = x(1) + x(2) + · · · + x(k)

• The cumulative product y is the vector having elements y(k), k = 1, 2, . . . , N

y(k) =k

n=1

x(n) = x(1) · x(2) · · ·x(k)

If X is a matrix with M rows and N columns with elements denoted x(m, n), m = 1, 2, . . . , M, n =1, 2, . . . , N , then

• The column sum y is the vector having elements y(n), n = 1, 2, . . . , N

y(n) =M∑

m=1

x(m, n) = x(1, n) + x(2, n) + · · · + x(M, n)

• The column product y is the vector having elements y(n), n = 1, 2, . . . , N

y(n) =M∏

m=1

x(m, n) = x(1, n) · x(2, n) · · ·x(M, n)

• The cumulative column sum Y is the matrix with M rows and N columns with elementsdenoted y(k, n), k = 1, 2, . . . , M, n = 1, 2, . . . , N

y(k, n) =k

m=1

x(m, n) = x(1, n) + x(2, n) + · · · + x(k, n)

• The cumulative column product Y is the matrix with M rows and N columns withelements denoted y(k, n), k = 1, 2, . . . , M, n = 1, 2, . . . , N

y(k, n) =k

m=1

x(m, n) = x(1, n) · x(2, n) · · ·x(k, n)

The Matlab functions implementing these mathematical functions are the following.

141

• The product y is the scalar

y =N∏

n=1

x(n) = x(1) · x(2) · · ·x(N)

• The cumulative sum y is the vector having elements y(k), k = 1, 2, . . . , N

y(k) =k

n=1

x(n) = x(1) + x(2) + · · · + x(k)

• The cumulative product y is the vector having elements y(k), k = 1, 2, . . . , N

y(k) =k

n=1

x(n) = x(1) · x(2) · · ·x(k)

If X is a matrix with M rows and N columns with elements denoted x(m, n), m = 1, 2, . . . , M, n =1, 2, . . . , N , then

• The column sum y is the vector having elements y(n), n = 1, 2, . . . , N

y(n) =M∑

m=1

x(m, n) = x(1, n) + x(2, n) + · · · + x(M, n)

• The column product y is the vector having elements y(n), n = 1, 2, . . . , N

y(n) =M∏

m=1

x(m, n) = x(1, n) · x(2, n) · · ·x(M, n)

• The cumulative column sum Y is the matrix with M rows and N columns with elementsdenoted y(k, n), k = 1, 2, . . . , M, n = 1, 2, . . . , N

y(k, n) =k

m=1

x(m, n) = x(1, n) + x(2, n) + · · · + x(k, n)

• The cumulative column product Y is the matrix with M rows and N columns withelements denoted y(k, n), k = 1, 2, . . . , M, n = 1, 2, . . . , N

y(k, n) =k

m=1

x(m, n) = x(1, n) · x(2, n) · · ·x(k, n)

The Matlab functions implementing these mathematical functions are the following.

141

• The product y is the scalar

y =N∏

n=1

x(n) = x(1) · x(2) · · ·x(N)

• The cumulative sum y is the vector having elements y(k), k = 1, 2, . . . , N

y(k) =k

n=1

x(n) = x(1) + x(2) + · · · + x(k)

• The cumulative product y is the vector having elements y(k), k = 1, 2, . . . , N

y(k) =k

n=1

x(n) = x(1) · x(2) · · ·x(k)

If X is a matrix with M rows and N columns with elements denoted x(m, n), m = 1, 2, . . . , M, n =1, 2, . . . , N , then

• The column sum y is the vector having elements y(n), n = 1, 2, . . . , N

y(n) =M∑

m=1

x(m, n) = x(1, n) + x(2, n) + · · · + x(M, n)

• The column product y is the vector having elements y(n), n = 1, 2, . . . , N

y(n) =M∏

m=1

x(m, n) = x(1, n) · x(2, n) · · ·x(M, n)

• The cumulative column sum Y is the matrix with M rows and N columns with elementsdenoted y(k, n), k = 1, 2, . . . , M, n = 1, 2, . . . , N

y(k, n) =k

m=1

x(m, n) = x(1, n) + x(2, n) + · · · + x(k, n)

• The cumulative column product Y is the matrix with M rows and N columns withelements denoted y(k, n), k = 1, 2, . . . , M, n = 1, 2, . . . , N

y(k, n) =k

m=1

x(m, n) = x(1, n) · x(2, n) · · ·x(k, n)

The Matlab functions implementing these mathematical functions are the following.

141

Homework

n  Factorial (iterative solution)

■ n!=n*(n-1)!

48