# 2015S001/User talk:Mzevallos/Homework 7

Important: Write out your answers by hand before checking them with MATLAB!

# 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 + 5; 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.

please give me an example, or help me solve this one, I don't understand what it's asking.

There are office hours and email availabilities.

# 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 = 2*q;  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; a = 2*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=1; for x=[1:4]; B(x) = x; end B  What does the resulting array look like?

B =

    1     2     3     4     4


The second 4 should not be there.

# 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?

B =

    0     1     2     3     4


# 6. Iteration

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

A(1) = 3
for i = [2,3,4,5]
A(i) = i*A(i-1)+i*i
end


A(2)= 10

A(3)= 39

A(4)= 172

A(5)= 885

# 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 12 + 22 + 32 + ... + 10002

result=0

for i=[1:1000].^2

sum(i)

result=result+i

end

# 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


a=[11:1:35]

for i=[1:5]

for j = [1:5]

a(i,j) = 1

variable = variable+1

end

end

This does not create the correct matrix.

# 9. nested for loops

Using a set of nested for loops and one or more if statements, 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


M = [11:15;16:20;21:25;26:30;31:35]

for i = [1:5]

for j = [1:5]

i=j

M(i,j)=0;

end

end

# 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) = j;
end
end
M


M =

   -1     0     1
-1     0     1


# 11. Nested for loop

Using MATLAB, do the following procedure: