1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#include <iostream>
using namespace std;
float ** multiply(float **A,int lA,int cA,float **B,int lB,int cB) {
int i,j,k;
float acc;
// Creating result R as a dinamic 2-D array
float **R = new float*[lA];
for(i=0;i<lA;i++) R[i] = new float[cB];
// Check if operation is possible and, if so, perfom it
if(cA == lB) {
for(i=0;i<lA;i++)
for(j=0;j<cB;j++){
acc = 0;
for(k=0;k<cA;k++) acc += A[i][k]*B[k][j];
R[i][j] = acc;
}
} else perror("Matrix A must have same number of columns than number of lines of matrix B");
return R;
}
float ** transpose(float **A,int lA,int cA) {
int i,j;
// Creating result T as a dinamic 2-D array
float **T = new float*[cA];
for(i=0;i<cA;i++) T[i] = new float[lA];
// Perfom it
for(j=0;j<cA;j++)
for(i=0;i<lA;i++)
T[j][i] =A[i][j];
return T;
}
int main(int argc, char* argv[]){
int i,j,N=3,M=5;
float ** Y;
// Initialize X
float ** X = new float *[N];
for(i=0;i<N;i++) X[i] = new float[M];
for(i=0;i<N;i++)
for(j=0;j<M;j++)
if (i == j) X[i][j] = i*j; else X[i][j] = i+j;
// Print array X
for(i=0;i<N;i++) {
for(j=0;j<M;j++) cout << X[i][j] << " ";
cout << endl;
}
cout << endl;
// Calculate Y
Y = multiply(X,N,M,transpose(X,N,M),M,N);
// Print array Y
for(i=0;i<N;i++) {
for(j=0;j<N;j++) cout << Y[i][j] << " ";
cout << endl;
}
cout << endl;
// Free memory (?)
for(i=0;i<3;i++) delete [] X[i];
delete [] *X;
for(i=0;i<3;i++) delete [] Y[i];
delete [] *Y;
// End of program
system("pause");
return 0;
}
|