Iterative Examples

Embed Size (px)

Citation preview

  • 8/12/2019 Iterative Examples

    1/20

    MATLABExamples of Iterative operations

    Ch E 111David A. Rockstraw, Ph.D., P.E.

    New Mexico State UniversityChemical Engineering Department

  • 8/12/2019 Iterative Examples

    2/20

    Nested Loop Statements

    % Nested loopsfori=1:4

    forj=1:3

    disp([i j i*j])end

    end

  • 8/12/2019 Iterative Examples

    3/20

    Nested Loop Statements

    clear Afori=1:n

    forj=1:n

    ifi < j

    A(i,j)=-1;

    elseifi > jA(i,j)=0;

    else

    A(i,j)=1;

    end

    endend

    A

  • 8/12/2019 Iterative Examples

    4/20

    Nested Loop Statements

    clear Afori=1:n

    forj=1:n

    ifi < j

    A(i,j)=-1;

    elseifi > jA(i,j)=0;

    else

    A(i,j)=1;

    end

    endend

    A AA=eye(n)-triu(ones(n),1)compare with the built-in function statement:

  • 8/12/2019 Iterative Examples

    5/20

    Example 1

    Write a for loop which calculates the sum the

    integers from 1 to 100 and the sum of the

    squares of the integers from 1 to 100.

    Print out only the results.

  • 8/12/2019 Iterative Examples

    6/20

    Example 1 Solutionsum1 = 0;

    sum2 = 0;

    fori = 1:100

    sum1 = sum1 + i;sum2 = sum2 + i^2;

    end

    sum1sum2

  • 8/12/2019 Iterative Examples

    7/20

    Example 2

    Determine the largest value of nsuch that

    6

    n

    1i

    210i

  • 8/12/2019 Iterative Examples

    8/20

    Example 2 Solution

    sum = 0;i = 0;

    while( sum < 1000000 )

    i = i + 1;

    sum = sum + i^2;

    end

    i

  • 8/12/2019 Iterative Examples

    9/20

    Example 3

    Find the integer value of nbetween 0 and 100

    such that

    minimumicosn

    0i

  • 8/12/2019 Iterative Examples

    10/20

    Example 3 SolutionSolve assuming that minimum occurs when n= 0. Then, for each

    n= 1, 2, ..., 100, compare the absolute value of the running sumwith that of the minimum absolute running sum currently found.If it is less, update the two variables.

    minimum_n = 0; % the sum when n = 0

    minimum_abs_sum = 1; % initially, the absolute value of |cos(0)|

    running_sum = 1; % cos(0) + ... + cos(n)

    forn = 1:100running_sum = running_sum + cos(n);

    if( abs( running_sum ) < minimum_abs_sum )

    minimum_n = n;

    minimum_abs_sum = abs( running_sum );

    end

    end

    minimum_n

    minimum_abs_sum

  • 8/12/2019 Iterative Examples

    11/20

    Example 4

    Continue subtracting (to a max of 1000 times)efrom until a value less than -10 is obtained.

    x = pi

    fori=1:1000

    x = x - exp(1)

    ifx < -10

    break;

    end

    end

  • 8/12/2019 Iterative Examples

    12/20

    Example 4

    Calculate the sum of those entries of the matrixM=[123;456;789]which lie in the

    upper-triangular portion (i.e., on or above

    diagonal).

  • 8/12/2019 Iterative Examples

    13/20

    Example 4 Solution

    M = [1 2 3; 4 5 6; 7 8 9];sum = 0;

    fori = 1:3

    forj = i:3sum = sum + M(i, j);

    end

    endsum

  • 8/12/2019 Iterative Examples

    14/20

    average.mclear

    % initialize - prepare to read 1st datum

    i = 1;

    % read and count data values

    data = input('Enter datum ("Enter" to stop): ');

    while~isempty(data) %data?

    y(i) = data; % - yes: store

    i = i+1; % countdata = input('Enter datum ("Enter" to stop): ');

    end

    % no more data - compute average

    sumY = sum(y); % compute sum

    [dummy, n] = size(y); % determine # values = # columns

    averageY = sumY/n;% print resultdisp(['the average of the 'num2str(n) ' values is '

    num2str(averageY)])

  • 8/12/2019 Iterative Examples

    15/20

    Integrate the sine function

    Write a program that approximates

    as

    N is the number of points used in the integration. You

    may need to use a for loop from 1 to N-1. Calculate

    the approximation using N = 5, 10, 20, and 50.

  • 8/12/2019 Iterative Examples

    16/20

    function intsin(N)

    functiony = intsin(N)

    % INTSIN - integrate sin(x) from 0 to pi

    y = (sin(0) + sin(pi))* pi/(2*N);

    forn = 1 : N-1y = y + sin(n*pi/N)*pi/N;

    end

  • 8/12/2019 Iterative Examples

    17/20

    Infinite sum

    Use a while loop to calculate the summation

    until the deviation from the exact answer is

    less than 0.1. Determine up to what n-value is

    needed to carry out the summation so that this

    deviation is achieved? How about a deviation

    of 0.01 and 0.001?

  • 8/12/2019 Iterative Examples

    18/20

    function pi2over6function[y,n] = pi2over6(tol)

    % PI2OVER6 - Approximates (pi)^2/6

    y=0;

    aim=pi*pi/6;

    n=0;

    while(abs(aim-y)>tol)

    n=n+1;

    y=y+1/(n*n);

    disp(sprintf('%g%s%g%s%g',n,' ',y,'

    ',aim-y))end

  • 8/12/2019 Iterative Examples

    19/20

    grcodi script

    Write a program that, given two positive integers N1 and N2,calculates their greatest common divisor. The greatestcommon divisor can be calculated easily by iterativelyreplacing the largest of the two numbers by the difference ofthe two numbers until the smallest of the two numbers reaches

    zero. When the smallest number becomes zero, the other givesthe greatest common divisor.

    You will need to use a while loop and an if-else statement. Thelargest of two numbers can be obtained using the built-infunction MAX(A,B). The smallest of two numbers can be

    obtained using the built-in function MIN(A,B).

  • 8/12/2019 Iterative Examples

    20/20

    grcodi script% GRCODI - determine greatest common divisor

    N1=input('first number = ');N2=input('second number = ');

    while(min(N1,N2)>0)

    if(N1 > N2)

    N1=N1-N2;else

    N2=N2-N1;

    end

    enddisp(sprintf('%s%g','GCD is ',max(N1,N2)))