Gauss-Seidel Method (Matlab)

  1. I need to solve the following problem using Matlab

    [​IMG]

    This is my code so far:

    Code (Text):
    clear all
    clc
    clf
    function x=GaussSeidel(A,b,y,N)
    n = length(y);
    for k = 1:N
        for i=1:n
            s=b(i);
            for j =1:i-1
                s=s-A(i,j)*y(j);
            end
            for j = i+1:n
                s=s-A(i,j)*y(j);
            end
            x(i)=s/A(i,i);
            x(i)=x(k);
        end
        y = x'
    end
     
    But I keep getting the following error:

    Code (Text):
    Error: File: Untitled.m Line: 4 Column: 1
    Function definitions are not permitted in this context.
    Why am I getting this error? What do I need to do?

    And my inputs would be:

    Code (Text):
    A=[-5 0 2 0 -1 ;
        0 9 0 3 0 ;
        2 0 5 0 2 ;
        0 -2 0 4 0 ;
        -1 0 7 0 7]
    b = [8;4;-8;-4;0]
    x0=[8;4;-8;-4;0]
    For N, how do I know many iterates N are necessary for this problem?

    Any help with the code is greatly appreciated.
     
  2. jcsd
  3. jhae2.718

    jhae2.718 1,160
    Gold Member

    You're defining a function in a script file. In MATLAB, functions are defined in a separate file with the same name as the function.

    Create a file GaussSeidel.m with the following:
    Code (Text):

    [color=#008000][b]function[/b][/color][color=#bbbbbb] [/color]x=[color=#0000FF]GaussSeidel[/color](A,b,y,N)[color=#bbbbbb]
    [/color]n = [color=#008000]length[/color](y);
    [color=#008000][b]for[/b][/color] k = 1:N
        [color=#008000][b]for[/b][/color] [color=#008000]i[/color]=1:n
            s=b([color=#008000]i[/color]);
            [color=#008000][b]for[/b][/color] [color=#008000]j[/color] =1:[color=#008000]i[/color][color=#666666]-[/color]1
                s=s[color=#666666]-[/color]A([color=#008000]i[/color],[color=#008000]j[/color])[color=#666666]*[/color]y([color=#008000]j[/color]);
            [color=#008000][b]end[/b][/color]
            [color=#008000][b]for[/b][/color] [color=#008000]j[/color] = [color=#008000]i[/color][color=#666666]+[/color]1:n
                s=s[color=#666666]-[/color]A([color=#008000]i[/color],[color=#008000]j[/color])[color=#666666]*[/color]y([color=#008000]j[/color]);
            [color=#008000][b]end[/b][/color]
            x([color=#008000]i[/color])=s[color=#666666]/[/color]A([color=#008000]i[/color],[color=#008000]i[/color]);
            x([color=#008000]i[/color])=x(k);
        [color=#008000][b]end[/b][/color]
        y = x[color=#666666]'[/color]
    [color=#008000][b]end[/b][/color]
     
    and a script file that calls the function.
     
  4. I'm not familiar with matlab, but I believe this is an incorrect implementation of the Gauss-Seidel method. This looks like the Jacobi method to me.

    I'm going to fool around with this and get back.
     
Know someone interested in this topic? Share a link to this question via email, Google+, Twitter, or Facebook