最近在用c++手搓神经网络,看了下网上的一些实现方法,都是基于索引实现的,给函数传入a[][10]或者(*a)[10],这种方法简洁明了,但是使用的时候,限制了数组第二维度的大小,如果要想重复使用还得用函数重载,所以自己整了个基于二级指针实现的方法。
#includeusing namespace std; void mul_array_2d(float** a,int a_row,int a_col,float** b,int b_row,int b_col,float** result_array) { if (a_col != b_row) { cout << "两个矩阵的大小不匹配,无法相乘" << endl; } else { for (int i = 0; i < a_row; i++) { for (int j = 0; j < b_col; j++) { for (int k = 0; k < a_col; k++) { //result_array[i][j] += a[i][k] * b[k][i]; //a[i][j]=a[i*n+j] //result_array[i * a_row + j] += a[i * a_col + k] * b[k * b_col + i]; *((float*)result_array + i * a_row + j) += *((float*)a + i * a_col + k) * *((float*)b + k * b_col + j); } } } } } int main() { float w[2][3] = {{1,2,3},{4,5,6}}; float x[3][2] = { {1,2},{3,4},{5,6} }; //cout << shape << endl; float wx[2][2] = { 0}; mul_array_2d((float**)w,2,3, (float**)x,3,2, (float**)wx); for (int i = 0; i < 2; i++) { cout << endl; for (int j = 0; j < 2; j++) { cout << wx[i][j] << " "; } } return 0; }



