简体   繁体   中英

How do I fix the index error in my Octave code?

I'm having issues with the index for my code. I'm trying to create a code on Octave for the power method (vector iteration) and the error: 'x(4): out of bound 3' keeps popping up at line 6.

    A=[6,-2,2,4;0,-4,2,2;0,0,2,-5;0,0,0,-3]
    b=[12;10;-9;-3]
    n=4
    for i=rows(A):-1:1
     for j=i+1:rows(A)
      x(i)=[b(i)-A(i,j)*x(j)]/A(i,i); #error: 'x(4): out of bound 3'
     endfor
    endfor 
    x

In the following line, note that you have x appearing twice; the first seeks to assign to it, but the second simply tries to access its value:

x(i) = [ b(i) - A(i,j) * x(j) ] / A(i,i);
⬑ assignment             ⬑ access

Assigning to an index that doesn't exist (yet) is absolutely fine; octave will simply fill in the intervening values with 'zeroes'. Eg

>> clear x
>> x(3) = 1    % output: x = [0, 0, 1]

However, trying to access an index which doesn't exist yet is an error, since there's nothing there to access. This results in an "out of bound" error (and, in its error message, octave is kind enough to tell you what the last legitimate index is that you can access in that particular array).

Therefore, this is an error:

>> clear x
>> x(3) = 1   % output: x = [0, 0, 1]
>> 1 + x(4)   % output: error: x(4): out of bound 3

Now going back to your specific code, you are trying to access something that doesn't exist yet. The reason it doesn't exist yet, is that you have set up your for loops such that j will achieve a higher value than i at a particular step, such that you are trying to access x(j) , which does not exist yet, in order to assign it to x(i) , where i < j. Therefore this results in an out of bounds error (you are trying to access index j when you only have up to i available).

In your particular case, octave informs you that this happened when j was 4 , and i was 3 .


PS: I will echo @HansHirse's implied warning here, that you should always pay attention to your variables, and clear them appropriately in your scripts, especially if you plan to run it many times. Never use a variable that you haven't defined (or cleared) beforehand. Otherwise, x here may not be undefined when you run your script, say, a second time. This leads to all sorts of problems, eg, your code works but for the wrong reasons, and then fails to work again when you run it the next day and x is now undefined. In this particular example, if you had an x in your workspace which had the right number of elements in it, your code would "work" but produce the wrong result, and you wouldn't know any better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM