以下程式示範兩個向量的內積算法:
(9) (7) (2 4 6 8 10) (5) = 110 (3) (1)因為我們還不會輸入數值,所以只能在宣告向量或矩陣的時候, 順便寫入數值。
#include <stdio.h> /* 示範向量內積 (demo-dot.c) */ #define N 5 main() { int x[N]={2,4,6,8,10}, y[N]={9,7,5,3,1}; int i, prod; for (i=0, prod=0; i<N; ++i) prod = prod + x[i]*y[i]; printf("%d\n", prod); }
以下程式示範矩陣向量的乘法:
(1 2 3 4) (6) ( 53) (5 6 7 8)*(5) = (141) (9 8 7 6) (7) (167) (4)
#include <stdio.h> /* 示範矩陣向量乘積 (demo-mvmul.c) */ #define M 3 #define N 4 main() { int A[M][N]={1,2,3,4,5,6,7,8,9,8,7,6}, x[N]={6,5,7,4}, y[M]; int i, j; for (i=0; i<M; ++i) { y[i] = 0; for (j=0; j<N; ++j) y[i] = y[i] + A[i][j]*x[j]; } for (i=0; i<M; ++i) printf("%5d\n", y[i]); }
習題
1 2 3 4 5 6 7 8 9 8 7 6輸出它的轉置矩陣。
(1 2 3 4) (7 8) (5 6 7 8) * (3 5) (9 8 7 6) (6 9) (4 4)