2015F001/Homework7

From CDS 130

Jump to: navigation, search

Contents

  1. For loop basic pattern
  2. For loop basic pattern
  3. For loop general pattern
  4. Arrays with a for loop
  5. Arrays with a for loop
  6. Iteration
  7. Iteration
  8. nested for-loops
  9. nested for loops
  10. Interpreting a Loop V
  11. Nested for loop

1. For loop basic pattern

y = 10;
y = y+37;
y = y + 2;
y = y * 2;
y = y + 2;
y = y * 2;
y = y + 2;
y = y * 2;
y = y + 2;
y = y * 2;
y = y * 99;





Identify the parts of the program that are repeated and hence a candidate for short-hand. Write a new version of the full program to the left using a for loop to reduce the length of the program.

2. For loop basic pattern

a = 0;
z = a+1;
a = z+1;
q = a+z;
z = a+1;
a = z+1;
q = a+z; 
z = a+1;
a = z+1;
q = a+z;


Identify the parts of this program that are repeated. Write a shorter version of the program to the left using a for loop.

3. For loop general pattern

i = 1;
a = 13;
i = 2;
a = i*i;
i = 3;
a = i*i;
i = 4;
a = i*i;
i = 5; 
a = i*i; 
a 


What is the final value of a? Write a short-hand version of the program to the left using a for loop. The final value of ashould be the same as the value obtained when running the long-hand version.

4. Arrays with a for loop

clear;
c=2;
B(0) =10; 
for x=[1:4];
  B(c) = B(c-1) + x ;
  c = c+1; 
end
B



What does the resulting array look like?

5. Arrays with a for loop

clear;
c=1;
for x=[1:4];
  c = c+1; 
  B(c) = x;
end
B


What does the resulting array look like?

6. Iteration

Write down the values of A(2), A(3), A(4), and A(5) after this loop has executed.

A(1) = 4
for i = 2:6
  A(i) = i*A(i-1)+i*i
end

7. Iteration

Create a variable called result. Assign it a value of zero. Then create a FOR loop such that when completed, the variable result holds the value of the sum 1 * 2 + 2 * 3 + 3 * 4 + ... + 1000 * 1001

8. nested for-loops

Using a set of nested for loops, create the following matrix

M =

   11    12    13    14    15
   16    17    18    19    20
   21    22    23    24    25
   26    27    28    29    30
   31    32    33    34    35

9. nested for loops

Using for-loops, modify the matrix above so that all values along the diagonal are zero.

M =

    0    12    13    14    15
   16     0    18    19    20
   21    22     0    24    25
   26    27    28     0    30
   31    32    33    34     0

10. Interpreting a Loop V

What are the values in the matrix M after executing this program?

for j = [-1:1]
  for i = [0:1]
    M(i+1,j+2) = i+j;
  end
 end 
M

11. Nested for loop

Using MATLAB, do the following procedure:

Download the Data file to your directory, name it as hw7.dat, and load it into your MATLAB session by: >> load hw7;

check what variables (i.e., arrays) are defined in this data file by running: >> whos

Now, applying double nested for-loops to calculate the total sum of all the elements contained in the matrix. Provide both the code and the final answer.

Personal tools