a concerned citizen
a concerned citizen

Reputation: 839

Basic for loop in Octave expanded

For some reason I can't get over this in Octave:

for i=1:n
  y(2:(i+1))=y(2:(i+1))-x(i)*y(1:i)
end;

If I break it down in steps (suppose n=3), wouldn't the loop look like this:

 i=1
y(2)=y(2)-x(1)*y(1)
 i=2
y(2)=y(2)-x(2)*y(1)
y(3)=y(3)-x(2)*y(2)
 i=3
y(2)=y(2)-x(3)*y(1)
y(3)=y(3)-x(3)*y(2)
y(4)=y(4)-x(3)*y(3)

Well, I must be wrong because the results are not good when doing the loop step by step, but for the life of me I can't figure it out where. Can someone please help me?

Upvotes: 1

Views: 139

Answers (1)

DJanssens
DJanssens

Reputation: 20699

First of all, forgive me my styling, I never used matrices/vector representations in Stack Overflow before. Anyway I hope this gives you an idea of how it internally works:

x = [1,2,3] 
y = [1,0,0,0]

Step 1:

the first loop will execute:

y(2)=y(2)-x(1)*y(1)

these are just scalar values, y(2) = 0, x(1) = 1, y(1) = 1. So y(2) = 0-1*1 = -1, which means that the 2nd position in vector y will become -1.

resulting in y = [1,-1,0,0]

Step 2:

The next loop will execute

enter image description here

Here y(2,3) and y(1,2) are vectors of size 2, where the values are the ones that correspond with the position in y. After calculating the new vector [-3,2] this will be assigned to the 2nd and 3th position in vector y. Resulting in the vector [1,-3,2,0].

Step 3: Repeat the step 2 but this time use vectors of size 3, and replace the outcome with the 2,3,4 position in the y matrix results in the final vector y being: [1,-6,11,-6]

Upvotes: 1

Related Questions