Matlab loops...help!

Thread Starter

natashakhan

Joined May 10, 2009
2
Hi there i have a question about for loops in matlab, i have a matlab exam very soon and am working through some questions and i don't understand how to reach the value for ires at the end of the loop. Hope someone can help.

Question:
Examine the following loops (without matlab) and determine the value in 'ires' at the end of each of the loops.

question1.

ires=0;
for index = 1:10
ires = ires+1;
end

question 2.

ires=0;
for index = 1:10
ires=ires+index;
end

question 3.

ires=0;
for index1=1:10
for index2=index1:10
if index2>6
break;
end
ires=ires+1;
end
end

Thankyou
 

Jynx

Joined Apr 24, 2009
1
First question:
for loop is used for repeating something a number of times... You give a vector as the only argument, and it passes through all of the elements. So the number of repeats is the number of elements.
so,
for i=1:10
somethingsomething

somethingsomething will repeat 10 times, because the vector 1:10 has 10 elements.

ires=ires+1 will repeat 10 times, and before the first time ires=0 (this is very important, you always have to initialize something before summing it).
So, 1 will be added to ires each time. ires = 10 when the loop finishes.

Second question:
Each time the loop repeats it takes the next element in the given argument vector. because i=1:10, the first time the loop is entered i will be 1, the second 2, and so on.

for i=1:10
ires=ires+index

so ires will be 1+2+3+4+...+10 = 55

Third question:
you have two for loops, so for each index1 from the first loop, the second loop will...loop :)
when index1=1, index2 goes from 1 to 10, when index1=2, index2=2:10 and so on.
Break statement will stop looping the loop, but only the one it is in (in this case it will stop the second, index2 loop).
So, each time index2 is some number from 7:10, the loop will break, and ires=ires+1 statement will be skipped.
now:
index1=1 the second loop should repeat 10 times, index2=1:10, but the loop will break when index2 reaches 7, so the ires statement will be executed 6 times, so now ires=6
index1=2 the second loop should repeat 9 times, index2=2:10, but the loop will break when index2 reaches 7, so the ires statement will be executed 5 times, so now ires=6+5=11
index1=3 the second loop should repeat 8 times, index2=3:10, but the loop will break when index2 reaches 7, so the ires statement will be executed 4 times, so now ires=11+4=15

and so on until index1 reaches 7, then the second loop will brake each time.
You get ires = 21

Hope this helps, I'm not very good at explaining when not personally showing :)
 
Top