我的目標是乘矩陣和向量VEC:乘以向量和矩陣
public static int[] vectorProduct(int[][] a, int[] x){
if(x.length != a[0].length)
throw new RuntimeException("Illegal matrix dimensions.");
int [] y = new int[a.length];
for(int i = 0; i<y.length;i++){
int sum=0;
for(int j = 0; j < a[0].length; j++){
sum+= a[i][j] * x[j];
}
}
return y;
}
我的主類看起來是這樣的:
public static void main(String[] args){
int [][] d = { {1,2,3},{1,2,3},{1,2,3}};
int [] vec = { 1,1,1 };
System.out.println("Vector product of matrix A and vecor x: ");
int[] v = MatMath.vectorProduct(d, vec);
print(v);
}
我應該得到[3, 6,9],但我得到[0,0,0]作爲我的輸出。我究竟做錯了什麼?
你永遠不會做的變量'sum'什麼。你可能應該把它放在你的'y'數組中,因爲你要返回它 – Gab