|
"CJ " <Jinkae@gmail.com> wrote in message
news:hco52b$35a$1@fred.mathworks.com...
> Hey guys I was trying to check some Successive Over Relaxation problems I
> did by hand using a function given in my numerical methods text and
> although I used the exact SAME code given in the text (I've checked and
> rechecked) I get the following error any time I try to use it:
> ??? Attempted to access xold(2); index out of bounds because
> numel(xold)=1.
>
> Error in ==> SOR at 17
> x = (1-w)*xold(j) + w*(C(j, :) * x + r(j));
>
> I've only been using MatLab for a month, so I'm not sure what this means
> exactly, but any advice would be greatly appreciated. Here is the book's
> code:
>
>
> function x = SOR(A, b, x0, w, tol, max_it)
> [ n, m ] = size(A); x = x0; C = -A;
> for i = 1:n
> C(i, i) = 0;
> end
> for i = 1:n
> C(i,1:n) = C(i,1:n)/A(i,i);
> end
> for i = 1:n
> r(i,1) = b(i)/A(i,i);
> end
> i = 1;
> disp(' i x1 x2 x3 ...')
> while (i <= max_it)
> xold = x; % save old solution from previous step
> for j = 1: n
> x(j) = (1-w)*xold(j) + w*(C(j, :) * x + r(j));
Apparently when you called this function, you passed in a scalar (a 1-by-1
array) for the x0 input. The first line of code assigned that value into
the variable x, and the "save old solution" link just before this loop
assigned that value into the variable xold.
Now the FOR loop executes. When j = 1, the line of code that's executed is
essentially:
x(1) = (1-w)*xold(1) + w*(C(1, :) * x + r(1));
and everything's fine, since xold and r have at least 1 element and C has at
least 1 column.
Now when j = 2, the line of code that's executed is:
x(2) = (1-w)*xold(2) + w*(C(2, :) * x + r(2));
Uh-oh. Now the code is asking for the second element of xold, but xold only
has one element. That's when you receive the error message you wrote above.
Either you need to update xold in the loop, or you need to specify a larger
x0, or you need to make some other fix. That's left as an exercise for you
to determine. When you determine what you need to do, you may want to add
some error checking at the top of the function to make sure that everything
has the sizes, shapes, etc. you expect them to have before you actually
start computing.
--
Steve Lord
slord@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ
|