Question

I have some trouble on setting of n-linear equations in matlab.I don't know how can I declare in matlab.I need matlab code for setting of n-linear equations..

Was it helpful?

Solution

You can write n-linear equations as one matrix equation to solve it. Here you can find great example: http://blogs.mathworks.com/pick/2007/09/13/matlab-basics-video-solving-linear-equations/ (video!)

See also these pages:
http://en.wikipedia.org/wiki/System_of_linear_equations
http://en.wikipedia.org/wiki/Matrix_equation

OTHER TIPS

You can solve a linear system in various ways, depending on whether there exists a unique solution or not.

A simple way is by reducing it to reduced-echelon form (rref).

Consider the system:

 x + 5y = 4
2x -  y = 1

You can write the coefficient matrix A, and the RHS, B as follows: (' is the transpose operator)

>> A = [1 5; 2 -1]

A =

     1     5
     2    -1

>> B = [4 1]'

B =

     4
     1

You can write it as an augmented matrix (A|B):

>> horzcat(A,B)

ans =

     1     5     4
     2    -1     1

And then find the REF(A|B)

>> rref(ans)

ans =

    1.0000         0    0.8182
         0    1.0000    0.6364

And hence x ~ .8182, y ~ .6364.

The absolutely fastest way to solve linear equations in MATLAB is simply to setup your equation on the form

AX = B

and then solve by

X = A\B

You can issue

help mldivide

to find more information on matrix division and what limitations it has.

A Code for iterative method Guase Seidel tol is error tolerance x0 is first guess for solution


 function seidel(A,b,x0,tol,itmax)
%Solve the system  Ax=b using the Gauss-Seidel iteration method.
clc
% =======================================================
% Programmer : A. Ziaee mehr
%

help seidel
n=length(b);
x=zeros(n,1);
%fprintf('\n')
disp('The augumented matrix is = ')
Augm=[A b]
Y=zeros(n,1);
Y=x0;   
for  k=1:itmax +1
    for ii=1:n
        S=0;
        for jj=1:ii-1
            S=S+A(ii,jj)*x(jj);
        end
        for jj=ii+1:n
            S=S+A(ii,jj)*x0(jj);
        end
        if (A(ii,ii)==0)
            break
        end
        x(ii)=(-S+b(ii))/A(ii,ii);
    end
    err=abs(norm(x-x0));
    rerr=err/(norm(x)+eps);
    x0=x;
    Y=[Y x];
    if(rerr<tol)
        break;
    end
end
% Print the results
if (A(ii,ii)==0)
    disp('division by zero')
elseif (k==itmax+1)
    disp('No convergence')
else
    %fprintf('\n')
    disp('The solution vector are : ')
    fprintf('\n')
    disp('iter    0       1            2          3           4    ... ');
    fprintf('\n')
    for ii=1:n
        fprintf('%1.0f= ',ii);
        fprintf('%10.6f ',Y(ii,1:k+1));
        fprintf('\n')
    end
    fprintf('\n')
    disp(['The method converges after ',num2str(k),' iterations to'])
    x
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top