Linear System Equation

สมมติเรามีระบบสมการเชิงเส้น  3 สมการดังนี้

การแก้สมการ โดยมือก็อาจจะไม่ยุ่งยาก เพื่อจะหาค่า x1,x2,x3 แต่ถ้าระบบสมการมีมากขึ้น ตั้งแต่ 4 จนถึงหลัก 10 หรือมากกว่า การคำนวณด้วยมือ ถือว่าเป็นเรื่องยุ่งยากและแทบจะเป็นไปไม่ได้เลย การใช้คอมพิวเตอร์ช่วย คงจะเป็นหนทางเดียวที่เราจะได้คำตอบ แต่ก็เหนื่อยเหมือนกันหากไม่มีความชำนาญ ในการเขียนโปรแกรมคำสั่งต่างๆ

ผู้เขียนได้ลองเขียน โปรแกรมสำหรับหาค่าตัวแปรที่เราไม่รู้ ในระบบสมการเชิงเส้น ซึ่งปกติเราจะใช้เทคนิคการแก้สมการ โดย Matrix ซึ่ง ผู้เขียนอยากแลกเปลี่ยน กับคนที่พอจะเข้าใจ Code คำสั่งของ MATLAB หรือ C ส่วนมากแล้วท่านที่เรียนในมหาวิทยาลัยทางด้านวิศวกรรม ก็คงจะมีโอกาสได้เรียนรู้มากกว่าทางสายอื่นๆ ซึ่งหากท่านมี Code อะไรที่ดีๆ ก็มาแลกเปลี่ยนกันครับ

 

function linear(A,b)

% Solve the matrix of linear equation..

%       Ax = b

% A : NxN matrix

% b : 1xN matrix

% General form

%         |a11 + a12 + .. a1n | | X1 |   | b1 |

%         |a21 + a22 + .. a2n | | X2 |   | b2 |      

%            .    .       .       .    =   .

%            .    .       .       .        .

%         |an1 + an2 + .. ann | | Xn |   | bn |

%

%       Example

%          A = [2,-3,1;4,-3,5;-2,1,4];

%          b = [9;5;6];

%          linear(A,b);

% If you type the above line on the command windows and then press ENTER,

% you will see the X Matrix that make the equation be true.

% Write By :

%      Chalong Srikaewsiew , Master degree of Mechatronics Engineering

%      Suranaree University of Technology , Nakornratchasima, Thailand

clc

C=inv(A);

N = length(A); % Size of the matrix

for i=1:1:N % Column loop

    xi=0;

    con=0;

    for j=1:1:N  % Row loop

         xi=b(j,1)*C(i,j);

         con=con+xi;

    end

    x(i)=con; %X Matrix

end

fprintf('\t X Matrix \n\n');

disp('--------------------');

table(:,1)=x;

fprintf('\t %4.4f \n',table');

disp('--------------------');

 

Step to entry the linear system equation.

>> A=[2,1,1;3,5,2;2,1,4]

 A =

      2     1     1

      3     5     2

      2     1     4

 >> b=[5;15;8]

 b =

      5

     15

      8

The result of the computation.

 

          X Matrix

    --------------------

             1.0000

             2.0000

             1.0000

    --------------------

 


[ HOME ]             [ CONTENTS ]    

Hosted by www.Geocities.ws

1