An interactive introduction to MATLAB

(Jeff_L) #1
5.2while loops 65

Exercise 8: Loops


Write your own scripts to perform the following tasks:



  1. a) Aforloop that multiplies all even numbers from 2 to 10.
    b) Awhileloop that multiplies all even numbers from 2 to 10.

  2. a) Aforloop that assigns the values 10, 20, 30, 40, and 50 to a vector.
    b) Awhileloop that assigns the values 10, 20, 30, 40, and 50 to a
    vector.
    c) Is there a simpler way to do this avoiding loops?

  3. Given the vectorx=[1 8 3 9 0 1]use aforloop to:
    a) Add up the values of all elements inx.
    b) Compute the cumulative sum, i.e1,9,12,21,21,22, of the elements
    inx.
    You can check your results using the built-in functionssumandcumsum.

  4. The factorial of a non-negative integer is defined as:


n!=n·(n− 1 )·(n− 2 )·...·1,

wheren!= 1 whenn= 0. For example, 5 != 5 · 4 · 3 · 2 · 1 which is 120.
Use aforloop to compute and print factorials. You should prompt
the user for a non-negative integer and check it is indeed non-negative.
There is a built-in function calledfactorial, therefore you should use
a different name for your script to avoid any confusion.


  1. Use awhileloop to determine and display the number of terms that it
    takes for the series,


SN=

∑N

n= 1

1

n^2 ,

to converge to within 0.01% of its exact value, which isS∞=π
2
6.

Exercise 8 Solutions


(http://www.eng.ed.ac.uk/teaching/courses/matlab/unit05/Ex8-
Solutions.shtml)

Free download pdf