非方阵点乘算法
基于<算法4>中的P12矩阵相乘(方阵), 探索非方阵点乘.
线代基础
能够点乘的矩阵, 一定满足 前行=后列
.
算法思考
解决矩阵运算问题, 切勿凭空想象. 应脚踏实地, 举个简单例子写在草稿纸上, 并观察 各矩阵下标变化规律
.
![在这里插入图片描述](https://img-blog.csdnimg.cn/416ecd12b7a54ee4b42865aa347b9b34.jpeg#pic_center)
c表示结果矩阵, 第一列表示a矩阵(前), 第二列表示b矩阵(后).
下标变化一致的用同一变量记录, 观察一个变量不变的情况下其他变量的变化规律, 一般可以找出循环嵌套.
比如a的第二维度与b的第一维度的变化相同, 用k变量记录. 在a的第一维度不变的情况下, b的第二维度有规律的变化, 则可以用循环去嵌套.
Java实现
import java.util.Arrays;
public class lab {
public static void main(String[] args) {
int[][] a = new int[2][3];
int[][] b = new int[3][2];
int n = 1;
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
a[i][j] = n;
++n;
}
}
System.out.println(Arrays.deepToString(a));
n = 1;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 2; j++) {
b[i][j] = n;
++n;
}
}
System.out.println(Arrays.deepToString(b));
int a_rows = a.length;
System.out.println(a_rows);
int b_columns = b[0].length;
System.out.println(b_columns);
if(a_rows != b_columns) {
System.out.println("Error Shape: Matrix A and B must have a same shape!");
System.exit(-1);
}
int N = a_rows;
int K = a[0].length;
int[][] c = new int[N][N];
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
for(int k = 0; k < K; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
System.out.println(Arrays.deepToString(c));
}
}
运行效果
[[1, 2, 3], [4, 5, 6]] # a
[[1, 2], [3, 4], [5, 6]] # b
2 # a_rows
2f # b_columns
[[22, 28], [49, 64]] # c