---
# System prepended metadata

title: 矩陣運算

---

# 矩陣運算

![](https://i.imgur.com/EDK9ADJ.png)


## fotran 代碼範例

```fotran=1
! 求解3x3矩陣 aMat = xb, aMat 已知 
program main
implicit none
real :: aMat(3,3) = reshape((/ 5.0,3.0,1.0,-1.0,8.0,1.0,2.0,-2.0,4.0/),(/3,3/))
!5	-1	 2
!3	 8	-2
!1	 1	 4

real :: Bmat(3)=(/12.0,-25.0,6.0/)
real :: x(3), x_temp(3), residual


integer :: i, j, k, nIters
integer :: zero(3)
write (*,*) "求解x"
DO j=1,3,1
     write (*,*) aMat(j,1),'* x1 + ', aMat(j,2) ,'* x2 + ', aMat(j,3),'* x3 = ',Bmat(j)
END Do

!------------設定初始 x------------------!
x= 50
!DO j=1,3,1
!    write (*,*) 'x',j,'=',x(j)
!END Do
!------------設定初始 x------------------!

!-----------設定次數------------------!
!write(*,*) '幾次?'
!read(*,*) nIters ! Number of iteractions
nIters=100
!-----------設定次數------------------!

write (*,*) "計算x GS方法"
DO i=1,nIters
         DO j=1,3
             
             zero(1)=1
             zero(2)=1
             zero(3)=1
             zero(j)=0
             x(j)=( Bmat(j)- zero(1)*aMat(j,1)*x(1)-zero(2)*aMat(j,2)*x(2)-  zero(3)*aMat(j,3)*x(3) )/aMat(j,j)



        END DO
        write(*,*) i,'residual:', abs(x(1)-x_temp(1)), abs(x(2)-x_temp(2)), abs(x(3)-x_temp(3))
          residual = 0
          DO k = 1, 3
               residual = residual + abs(x(k)-x_temp(k))
          END DO
         if(residual<0.0001) exit
         x_temp = x
END DO

write(*,*) 'xResult:', x(1), x(2), X(3)

stop
END program main

```

```shell=
 求解x
   5.00000000     * x1 +   -1.00000000     * x2 +    2.00000000     * x3 =    12.0000000
   3.00000000     * x1 +    8.00000000     * x2 +   -2.00000000     * x3 =   -25.0000000
   1.00000000     * x1 +    1.00000000     * x2 +    4.00000000     * x3 =    6.00000000
 計算x GS方法
           1 residual:   7.59999990       12.2250004      0.343750000
           2 residual:   12.3074999       17.0293751       1.18046868
           3 residual:   3.87806225       1.74939036      0.532168031
           4 residual:  0.137010872       8.16628933E-02   5.46684265E-02
           5 residual:   3.81998420E-02   2.79920101E-02   2.55203247E-03
           6 residual:   4.57751751E-03   1.07860565E-03   8.74757767E-04
           7 residual:   1.34110451E-04   2.68936157E-04   3.36170197E-05
           8 residual:   6.72340393E-05   3.36170197E-05   8.46385956E-06
           9 residual:   3.57627869E-06   7.15255737E-07   1.07288361E-06
 xResult:   1.00000036      -3.00000024       2.00000000
```