MATRIX *matrix_scale(MATRIX *a,double s) { //MATRIX *matrix_allocate(); MATRIX *b; int a_r,a_c; /* simplify the row and col variables */ a_r = a->rows; a_c = a->cols; /* do the different type cases with a switch statement */ switch(a->element_size) { case sizeof(short): /* if a int, b is float */ b = matrix_allocate(a_r,a_c,sizeof(float)); SCALE_MAT(a,b,s,a_r,a_c,0,0,short,float) break; case sizeof(float): /* a float, b float */ b = matrix_allocate(a_r,a_c,sizeof(float)); SCALE_MAT(a,b,s,a_r,a_c,0,0,float,float) break; case sizeof(double): /* a double, b double */ b = matrix_allocate(a_r,a_c,sizeof(double)); SCALE_MAT(a,b,s,a_r,a_c,0,0,double,double) } return(b); }
MATRIX *matrix_crop(MATRIX *a,int row_offset,int col_offset,int rows,int cols) { //MATRIX *matrix_allocate(); MATRIX *b; /* check the row and col variables */ if((rows + row_offset) > a->rows || (cols + col_offset) > a->cols) return(NULL); /* allocate the output sub-matrix */ b = matrix_allocate(rows,cols,a->element_size); /* do the different type cases with a switch statement */ switch(a->element_size) { case sizeof(short): SCALE_MAT(a,b,1,rows,cols,row_offset,col_offset,short,short) break; case sizeof(float): SCALE_MAT(a,b,1,rows,cols,row_offset,col_offset,float,float) break; case sizeof(double): SCALE_MAT(a,b,1,rows,cols,row_offset,col_offset,double,double) } return(b); }
// Set up a matrix structure matrix zero_matrix(unsigned int n, unsigned int m) { matrix mat; if((mat = malloc(sizeof(*mat))) == NULL) { perror("Error allocating memory"); return NULL; } // Set offsets mat->x_offset = 1; mat->y_offset = 1; // Make sure dimensions are >=1 if(n < 1 || m < 1) { fprintf(stderr,"Error: dimensions must be >=1\n"); return NULL; } mat->n = n; mat->m = m; // Allocate space for the actual matrix // errors are identified by matrix_allocate(), // so this is just to clean up if((mat->A = matrix_allocate(n,m)) == NULL) { free(mat); return NULL; } return mat; }
void read_file2(FILE* file){ fscanf(file,"row=%d col=%d",&n2,&m2); matrix_allocate(&matrix2,n2,m2); int i,j; for(i=0;i<n2;i++){ for(j=0;j<m2;j++){ fscanf(file,"%lf",&matrix2[i][j]); } } }
void read_file1(FILE* file){ fscanf(file,"row=%d col=%d",&n1,&m1); matrix_allocate(&matrix1,n1,m1); int i,j; for(i=0;i<n1;i++){ for(j=0;j<m1;j++){ fscanf(file,"%lf",&matrix1[i][j]); } } }
MATRIX *matrix_transpose(MATRIX *A) { //MATRIX *matrix_allocate(); MATRIX *At; short **ai,**ait; float **af,**aft; double **ad,**adt; int i,j; /* allocate transposed output space of same type */ At = matrix_allocate(A->cols,A->rows,A->element_size); switch(A->element_size) { case sizeof(short): ai = (short **)A->ptr; ait = (short **)At->ptr; for(i = 0 ; i < A->rows ; i++) for(j = 0 ; j < A->cols ; j++) ait[j][i] = ai[i][j]; break; case sizeof(float): af = (float **)A->ptr; aft = (float **)At->ptr; for(i = 0 ; i < A->rows ; i++) for(j = 0 ; j < A->cols ; j++) aft[j][i] = af[i][j]; break; case sizeof(double): ad = (double **)A->ptr; adt = (double **)At->ptr; for(i = 0 ; i < A->rows ; i++) for(j = 0 ; j < A->cols ; j++) adt[j][i] = ad[i][j]; } return(At); }
double matrix_det(MATRIX *A) { //MATRIX *matrix_allocate(); void matrix_free(); MATRIX *Adet; double **a; double *a_ptr; double det,big,pivot_inverse,temp,abs_element; int n,row,col,swap_row,pivot; if(A->rows != A->cols) return(0.0); /* check pointer */ if(!A->ptr) return(0.0); /* size of square matrix */ n = A->rows; /* allocate space for the determinant calculation matrix */ Adet = matrix_allocate(n,n,sizeof(double)); /* copy to double matrix for calculations */ switch(A->element_size) { case sizeof(short): SCALE_MAT(A,Adet,1,n,n,0,0,short,double) break; case sizeof(float): SCALE_MAT(A,Adet,1,n,n,0,0,float,double) break; case sizeof(double): SCALE_MAT(A,Adet,1,n,n,0,0,double,double) break; default: return(0.0); } a = (double **)Adet->ptr; /* initialize the answer */ det = 1.0; for(pivot = 0 ; pivot < n-1 ; pivot++) { /* find the biggest Helpers::absolute pivot */ big = fabs(a[pivot][pivot]); swap_row = 0; /* initialize for no swap */ for(row = pivot + 1; row < n ; row++) { abs_element = fabs(a[row][pivot]); if(abs_element > big) { swap_row = row; big = abs_element; } } /* unless swap_row is still zero we must swap two rows */ if(swap_row != 0) { a_ptr = a[pivot]; a[pivot] = a[swap_row]; a[swap_row] = a_ptr; /* change the sign of determinant because of swap */ det = -det*a[pivot][pivot]; } else { /* calculate the determinant by the product of the pivots */ det = det*a[pivot][pivot]; } /* if almost singular matrix, give up now */ if(fabs(det) < 1.0e-50) return(det); pivot_inverse = 1.0/a[pivot][pivot]; for(col = pivot + 1 ; col < n ; col++) { a[pivot][col] = a[pivot][col]*pivot_inverse; } for(row = pivot + 1 ; row < n ; row++) { temp = a[row][pivot]; for(col = pivot + 1 ; col < n ; col++) { a[row][col] = a[row][col] - a[pivot][col]*temp; } } } /* last pivot, no reduction required */ det = det*a[n-1][n-1]; /* free up the calculation matrix */ matrix_free(Adet); return(det); }
MATRIX *matrix_invert(MATRIX *A) { //MATRIX *matrix_allocate(); MATRIX *Ai; double **a; double big,pivot_inverse,temp,abs_element; int *pivot_flag,*swap_col,*swap_row; int i,n,row,col,swap,irow,icol; /* check for square matrix */ if(A->rows != A->cols) return(NULL); /* check pointer */ if(!A->ptr) return(NULL); /* size of square matrix */ n = A->rows; /* allocate space for the inverse */ Ai = matrix_allocate(n,n,sizeof(double)); /* copy to double matrix */ switch(A->element_size) { case sizeof(short): SCALE_MAT(A,Ai,1,n,n,0,0,short,double) break; case sizeof(float): SCALE_MAT(A,Ai,1,n,n,0,0,float,double) break; case sizeof(double): SCALE_MAT(A,Ai,1,n,n,0,0,double,double) break; default: return(NULL); } a = (double **)Ai->ptr; /* allocate index arrays and set to zero */ pivot_flag = (int *) calloc(n,sizeof(int)); swap_row = (int *) calloc(n,sizeof(int)); swap_col = (int *) calloc(n,sizeof(int)); if(!pivot_flag || !swap_row || !swap_col) return(NULL); for(i = 0 ; i < n ; i++) { /* n iterations of pivoting */ /* find the biggest pivot element */ big = 0.0; for(row = 0 ; row < n ; row++) { if(!pivot_flag[row]) { /* only unused pivots */ for(col = 0 ; col < n ; col++) { if(!pivot_flag[col]) { abs_element = fabs(a[row][col]); if(abs_element >= big) { big = abs_element; irow = row; icol = col; } } } } } pivot_flag[icol]++; /* mark this pivot as used */ /* swap rows to make this diagonal the biggest Helpers::absolute pivot */ if(irow != icol) { for(col = 0 ; col < n ; col++) { temp = a[irow][col]; a[irow][col] = a[icol][col]; a[icol][col] = temp; } } /* store what we swaped */ swap_row[i] = irow; swap_col[i] = icol; /* bad news if the pivot is zero */ if(a[icol][icol] == 0.0) return(NULL); /* divide the row by the pivot */ pivot_inverse = 1.0/a[icol][icol]; a[icol][icol] = 1.0; /* pivot = 1 to avoid round off */ for(col = 0 ; col < n ; col++) a[icol][col] = a[icol][col]*pivot_inverse; /* fix the other rows by subtracting */ for(row = 0 ; row < n ; row++) { if(row != icol) { temp = a[row][icol]; a[row][icol] = 0.0; for(col = 0 ; col < n ; col++) a[row][col] = a[row][col]-a[icol][col]*temp; } } } /* fix the affect of all the swaps for final answer */ for(swap = n-1 ; swap >= 0 ; swap--) { if(swap_row[swap] != swap_col[swap]) { for(row = 0 ; row < n ; row++) { temp = a[row][swap_row[swap]]; a[row][swap_row[swap]] = a[row][swap_col[swap]]; a[row][swap_col[swap]] = temp; } } } /* free up all the index arrays */ free((char *)pivot_flag); free((char *)swap_row); free((char *)swap_col); return(Ai); }
MATRIX *matrix_mult(MATRIX *A,MATRIX *B) { //MATRIX *matrix_allocate(); MATRIX *C; int a_r,a_c,b_c; if(B->rows != A->cols) return(NULL); if(!A->ptr) return(NULL); if(!B->ptr) return(NULL); /* simplify the row and col variables */ a_r = A->rows; a_c = A->cols; b_c = B->cols; /* allocate C to be of the highest ranking type of A and B (largest element size gives the highest rank ) */ if(A->element_size > B->element_size) C = matrix_allocate(a_r,b_c,A->element_size); else C = matrix_allocate(a_r,b_c,B->element_size); /* do the 9 type cases of A and B with 2 nested switch statements */ switch(A->element_size) { case sizeof(short): switch(B->element_size) { case sizeof(short): /* C int, A int, B int */ MULT_MAT(A,B,C,a_r,a_c,b_c,short,short,short) break; case sizeof(float): /* C float, A int, B float */ MULT_MAT(A,B,C,a_r,a_c,b_c,short,float,float) break; case sizeof(double): /* C double, A int, B double */ MULT_MAT(A,B,C,a_r,a_c,b_c,short,double,double) } break; case sizeof(float): switch(B->element_size) { case sizeof(short): /* C float, A float, B int */ MULT_MAT(A,B,C,a_r,a_c,b_c,float,short,float) break; case sizeof(float): /* C float, A float, B float */ MULT_MAT(A,B,C,a_r,a_c,b_c,float,float,float) break; case sizeof(double): /* C double, A float, B double */ MULT_MAT(A,B,C,a_r,a_c,b_c,float,double,double) } break; case sizeof(double): switch(B->element_size) { case sizeof(short): /* C double, A double, B int */ MULT_MAT(A,B,C,a_r,a_c,b_c,double,short,double) break; case sizeof(float): /* C double, A double, B float */ MULT_MAT(A,B,C,a_r,a_c,b_c,double,float,double) break; case sizeof(double): /* C double, A double, B double */ MULT_MAT(A,B,C,a_r,a_c,b_c,double,double,double) } } return(C); }
histogram *jackwerth::compute_histogram(double lo, double hi, double increment) { volatile double lokappa = 0.0; volatile double hikappa = 1.0; int done = 0; // OK, first we need to calculate "J" the number of entries in the computed // volatilities array. (And, the matrix size as well) int J = 1+(int)(1+((hi - lo) / increment)); // I is the number of observed values, so that's simply _num_observed. double **baseA = matrix_allocate(J,J,0.0); double **A = matrix_allocate(J,J,0.0); double *X = vector_allocate(J,0.0); double *B = vector_allocate(J,0.0); double final_probs[J]; for (int j = 0; j < J; ++j) { int values[] = { 1,-4,6,-4,1}; for (int k = -2; k <= 2; ++k) { int actual_k = j + k; int offset = values[k+2]; if (actual_k < 0) actual_k = 0; if (actual_k >= J) actual_k = (J-1); baseA[j][actual_k] = offset; } } int iters = 128; while (!done) { double kappa = lokappa + (hikappa - lokappa) / 2.0; double prop = (kappa - lokappa) / (hikappa - lokappa); done = (prop == 0.0); // OK, Kappa is _Binesh's_ invention. Kappa relates to lambda like so: // kappa = lambda / (1+lambda). // so, lambda = kappa / (1-kappa) // Why? This way Kappa = 0 is effectively reducing lambda to 0. // Kappa = 1 tho, would be lambda at a "infinite" value. (In reality, we'd // likely start at kappa = 0.9 and work till we didn't have any negative values. double lambda = kappa / (1-kappa); for (int i = 0; i < J; ++i) { B[i] = 0.0; for (int j = 0; j < J; ++j) A[i][j] = baseA[i][j]; } // Now, we have to add all the I's. // we have to make sure that each option here is actually // exactly on our "grid" (or rather on our discretized line). double coeff = lambda * (J * 1.0) / (_num_observed * increment * increment * increment * increment); for (int i = 0; i < _num_observed; ++i) { int index = (int)(0.5+((_observed_strikes[i] - lo) / increment)); // Now, _observed_strikes[i] - (index * increment + lo) should be "close" to zero. double trust_but_verify = _observed_strikes[i] - (index * increment + lo); if (!(((-increment/100) < trust_but_verify) && (trust_but_verify < (increment/100)))) { fprintf(stderr,"%s: %d: _observed_strikes[%d] = %.7g\n",__FILE__,__LINE__,i,_observed_strikes[i]); fprintf(stderr,"%s: %d: lo = %.7g\n",__FILE__,__LINE__,lo); fprintf(stderr,"%s: %d: index = %d\n",__FILE__,__LINE__,index); fprintf(stderr,"%s: %d: increment = %.7g\n",__FILE__,__LINE__,increment); fprintf(stderr,"%s: %d: trust_but_verify = %.7g\n",__FILE__,__LINE__,trust_but_verify); } assert(((-increment/100) < trust_but_verify) && (trust_but_verify < (increment/100))); double Aii = A[index][index]; double Bi = B[index]; A[index][index] = Aii+coeff; B[index] = Bi+coeff*_observed_volatilities[i]; } // OK, now we have to solve for X. just_svd(A,J,B,X); /* Now, the probabilities, according to page 66 of Jackwerth are Exp[r T] D[D[BS[S,K,r,q,V[K],T],K],K] if I read that right. I don't _like_ his version, because it uses r as the percentaged based return rather than an Exp[r] type r (ditto for q, the dividend yield.) Hopefully, mine will return the same results. We'll see in a minute. (I'm also not so sure I understand _why_ the equation works. _If_ it works, I'll have to look into _why_.) My version (or rather, mathematica's version _does_ work. However, Jackwerth's A. also works, B. is provably _equal_ to the mathematica version (implement both, and subtracting mathematica from jackwerth yields 0 in mathematica) and C. is less prone to numeric errors. */ const double *volatility = X; // just a renaming of the variable, really. double probs[J]; probs[0] = 0.0; probs[(J-1)] = 0.0; double total = 0.0; for (int j = 1; j < (J-1); ++j) { double V_K = volatility[j]; double dVdK = (volatility[j+1] - volatility[j-1]) / (2*increment); double dV2dK2 = (volatility[j-1] - 2*volatility[j] + volatility[j+1]) / (increment*increment); double q = _q; double r = _r; double T = _t; double S = _S; double K = lo + increment * j; double d1j = (log(S/K) + (r - q + V_K*V_K / 2.0) * T) / (V_K * sqrt(T)); double d2j = d1j - V_K * sqrt(T); probs[j] = ( (pdf(d2j)*(1+2*K * sqrt(T)*d1j*dVdK)/(K*V_K*sqrt(T))) + (S * exp(T*(r-q))*sqrt(T)*pdf(d1j)*(dV2dK2 + d1j*d2j * dVdK*dVdK / V_K)) ); total += probs[j]; } int negative_probs = 0; for (int j = 0; j < J; ++j) { probs[j] = probs[j] / total; if (probs[j] < 0.0) negative_probs = 1; } if (!negative_probs) { for (int j = 0; j < J; ++j) final_probs[j] = probs[j]; } if (negative_probs) { done = 0; hikappa = kappa; } else lokappa = kappa; iters--; if (iters < 0) done = 1; } vector_free(B); B = NULL; vector_free(B); B = NULL; vector_free(X); X = NULL; matrix_free(baseA); baseA = NULL; matrix_free(A); A = NULL; /* * OK, final_probs should contain our list of final probabilities. * Build a histogram: * The histogram will contain J bins, so it has to contain J+1 fenceposts. * The fenceposts should be log(K/S) values. */ double fenceposts[J+1]; /* Binesh - 2008-10-10 - Ugh. for (int j = 0; j < J+1; ++j) yields a "cannot optimize possibly infinite loops" error. So, that's why there's a "volatile" in front of int. */ for (volatile int j = 0; j < J+1; ++j) { double K = lo + increment * j - increment/2.0; double S = _S; double l = log(K/S); fenceposts[j] = l; } histogram *retVal = new histogram(J,fenceposts); for (int j = 0; j < J; ++j) { double K = lo + increment * j - increment/2.0; double S = _S; double l = log(K/S); retVal->accumulate(l,final_probs[j]); } return(retVal); }
bool clsLinearModelEM::CalculateRegressionFunction(std::vector<clsRegressionPts> &vectPoints) { mint_percent_complete = 0 ; int numPoints = vectPoints.size() ; if (mobj_X != NULL) { matrix_free(mobj_X) ; matrix_free(mobj_Y) ; matrix_free(mobj_Weights) ; matrix_free(mobj_XTranspose) ; } mobj_X = matrix_allocate(numPoints, 2, sizeof(double)) ; mobj_Y = matrix_allocate(numPoints, 1, sizeof(double)) ; mobj_Weights = matrix_allocate(numPoints, numPoints, sizeof(double)) ; mdbl_percent_normal = 0.5 ; // set up X, Y and weights vector. double **ptrMatrixX = (double **) mobj_X->ptr ; double **ptrMatrixY = (double **) mobj_Y->ptr ; double **ptrMatrixWeights = (double **) mobj_Weights->ptr ; double sumX = 0 ; double sumXX = 0 ; for (int index = 0 ; index < numPoints ; index++) { clsRegressionPts currentPoint = vectPoints[index] ; ptrMatrixX[index][0] = currentPoint.mdbl_x ; sumX += currentPoint.mdbl_x ; sumXX += (currentPoint.mdbl_x * currentPoint.mdbl_x ); ptrMatrixX[index][1] = 1 ; ptrMatrixY[index][0] = currentPoint.mdbl_y ; for (int colNum = 0 ; colNum < numPoints ; colNum++) { ptrMatrixWeights[index][colNum] = 0 ; } ptrMatrixWeights[index][index] = 1 ; mint_percent_complete = (10 * index)/numPoints ; } if (sumX * sumX == numPoints * sumXX) { mdbl_intercept = 0 ; mdbl_slope = 0 ; throw "All X values cannot be same for linear regression" ; } mobj_XTranspose = matrix_transpose(mobj_X) ; mint_percent_complete = 20 ; CalculateSlopeInterceptEstimates(); CalculateInitialStdev() ; // matrices are set up. for (int iterationNum = 0 ; iterationNum < NUM_ITERATIONS_TO_PERFORM ; iterationNum++) { mint_percent_complete = 20 + (80*(iterationNum+1))/NUM_ITERATIONS_TO_PERFORM ; CalculateSlopeInterceptEstimates() ; CalculateProbabilitiesAndWeightMatrix() ; if (mdbl_percent_normal < 0.01) return false ; } matrix_free(mobj_X) ; matrix_free(mobj_Y) ; matrix_free(mobj_Weights) ; matrix_free(mobj_XTranspose) ; return true ; }
int main(int argc, char **argv) { int int_max_alfa,step; int pipe_disp[2], pid; FILE *output; printf("%s",triangle_4); getopt_dec(argc, argv); if ((input = fopen(filein, "r")) == NULL) fatal("\n Can't open input file"); unpack(-2,input); /*Initialize unpack */ N_BITALFA = (int)unpack(4,input); N_BITBETA = (int)unpack(4,input); min_size = (int)unpack(7,input); max_size = (int)unpack(7,input); SHIFT = (int)unpack(6,input); image_width = (int)unpack(12,input); image_height = (int)unpack(12,input); int_max_alfa = (int)unpack(8,input); bits_per_coordinate_w = ceil(log(image_width / SHIFT ) / log(2.0)); bits_per_coordinate_h = ceil(log(image_height / SHIFT ) / log(2.0)); zeroalfa = 0; MAX_ALFA = (double) int_max_alfa / (double)(1 << 8) * ( 8.0) ; max = image_height; min = image_width; if(image_width > image_height ) { min = image_height; max = image_width; } virtual_size = 1 << (int) ceil(log((double) max) / log(2.0)); trans = &fractal_code; printf("\n Reading %s ... ",filein); fflush(stdout); read_transformations(0,0,virtual_size); printf("done\n"); fflush(stdout); printf(" Original image size: %dx%d\n",image_width,image_height); image_width = (int) rint((zoom * image_width)); image_height = (int) rint((zoom * image_height)); if(zoom != 1.0) { printf(" Zooming image to : %dx%d\n",image_width,image_height); fflush(stdout); } matrix_allocate(image,2+image_width,2+image_height,PIXEL) matrix_allocate(image1,2+image_width,2+image_height,PIXEL) if(piramidal) { min *= zoom; step = SHIFT * floor(zoom); if(step == 0) step = 1; lev = 0; while(1){ if(min < 200 || (step & 1)) break; min >>= 1; step >>= 1; lev++; } printf("\n %d level piramid\n",lev); iterative_decoding(lev,iterations,zoom); /* Decode at low resolution */ piramidal_decoding(lev); /* Increase resolution */ if(quality) iterative_decoding(0,2,1.0); } else
int main(int argc, char *argv[]) { arg0 = argv[0]; if (argc != 3) { fprintf(stderr, "Usage: %s file1 file2\n", arg0); exit(1); } FILE *fptrain = efopen_ro(argv[1]); int row, col; if (fscanf(fptrain, "%d", &col) != 1) err_readerr_int("col"); col++; if (fscanf(fptrain, "%d", &row) != 1) err_readerr_int("row"); char ch; /* Input format - file 1 ** Assuming row = 5, col = 7 (so col variable = 8 after 7 read from file) ** row col ** V00 V01 V02 V03 V04 V05 V06 V07 V08 V09 ** V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 ** V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 ** V30 V31 V32 V33 V34 V35 V36 V37 V38 V39 ** V40 V41 V42 V43 V44 V45 V46 V47 V48 V49 ** Values may be comma terminated; the row/col values may not. */ /* double trainX[row][col]; double trainY[row][1]; double trainXtrans[col][row]; double trainXtemp[row][row]; double trainXinden[col][col * 2]; double trainXinverse[row][row]; double trainXinvXt[col][row]; double weight[row][1]; double testM[testrows][col]; double prices[testrows][1]; */ // creates the original X and Y matrix double (*trainX)[col] = matrix_allocate(row, col); double (*trainY)[1] = matrix_allocate(row, 1); for (int i = 0; i < row; i++) { trainX[i][0] = 1.000000; for (int j = 1; j < col; j++) { if (fscanf(fptrain, "%lf%c", &trainX[i][j], &ch) != 2) err_readerr("trainX", i, j); } if (fscanf(fptrain, "%lf%c", &trainY[i][0], &ch) != 2) err_readerr("trainY", i, 0); } fclose(fptrain); // creates the X transposed matrix double (*trainXtrans)[row] = matrix_allocate(col, row); matrix_transpose(row, col, trainX, trainXtrans); // multiplies X and X transposed double (*trainXtemp)[row] = matrix_allocate(row, row); matrix_multiply(row, col, row, trainX, trainXtrans, trainXtemp); // finds the identity matrix of X times X transposed double (*trainXiden)[col * 2] = matrix_allocate(col, col * 2); for (int i = 0; i < col; i++) { for (int j = 0; j < col; j++) { trainXiden[i][j] = trainXtemp[i][j]; } for (int j = col; j < col * 2; j++) { if (j == i + col) { trainXiden[i][j] = 1.000000; } else { trainXiden[i][j] = 0.000000; } } } // finds the inverse of X times X transposed through Gauss Jordan Elimination for (int i = 0; i < col; i++) { double divscalar = trainXiden[i][i]; for (int j = 0; j < col * 2; j++) { if (trainXiden[i][j] != 0) { trainXiden[i][j] = trainXiden[i][j] / divscalar; } } for (int k = 0; k < col; k++) { if (i != k) { double subscalar = trainXiden[k][i]; for (int j = 0; j < col * 2; j++) { trainXiden[k][j] = trainXiden[k][j] - subscalar * trainXiden[i][j]; } } } } double (*trainXinverse)[row] = matrix_allocate(row, row); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { trainXinverse[i][j] = trainXiden[i][j + col]; } } double (*trainXinvXt)[row] = matrix_allocate(col, row); matrix_multiply(col, row, col, trainXinverse, trainXtrans, trainXinvXt); // multiples (trainXinvXt) by Y double (*weight)[1] = matrix_allocate(row, 1); for (int i = 0; i < col; i++) { for (int s = 0; s < row; s++) { weight[i][0] += trainXinvXt[i][s] * trainY[s][0]; } } /* Input format - file 2 ** Assuming testrow = 5, col = 8 (because of col++) ** row col ** V00 V01 V02 V03 V04 V05 V06 V07 ** V10 V11 V12 V13 V14 V15 V16 V17 ** V20 V21 V22 V23 V24 V25 V26 V27 ** V30 V31 V32 V33 V34 V35 V36 V37 ** V40 V41 V42 V43 V44 V45 V46 V47 ** Values may be comma terminated; the row/col values may not. */ FILE *fptest = efopen_ro(argv[2]); int testrows; if (fscanf(fptest, "%d", &testrows) != 1) err_readerr_int("testrows"); // creates the test file matrix double (*testM)[col] = matrix_allocate(testrows, col); for (int i = 0; i < testrows; i++) { testM[i][0] = 1.000000; for (int j = 1; j < col; j++) { if (fscanf(fptest, "%lf%c", &testM[i][j], &ch) != 2) err_readerr("testM", i, j); } } fclose(fptest); double (*prices)[1] = matrix_allocate(testrows, 1); for (int i = 0; i < testrows; i++) { double num = 0.0; for (int s = 0; s < col; s++) { num += testM[i][s] * weight[s][0]; } prices[i][0] = num; } /* Print result */ for (int i = 0; i < testrows; i++) { printf("%.0lf\n", prices[i][0]); } free(trainX); free(trainY); free(trainXtrans); free(trainXtemp); free(trainXiden); free(trainXinverse); free(trainXinvXt); free(weight); free(testM); free(prices); return 0; }
int main(int args_num,char *args[]) { //modify output file name char output[1000]; if(args_num==4){ int i=0; for(i=0;i<strlen(args[3]);i++){ if(args[3][i]=='.'){ output[i]='\0'; break; } output[i]=args[3][i]; } } // open files char *file_dir = malloc(sizeof(char) * 1000); FILE* file1; FILE* file2; FILE* file3; FILE* file4; //open file 1 if(args_num>=2){ getcwd(file_dir,1000); strcat(file_dir,"/"); strcat(file_dir,args[1]); file1=fopen(file_dir,"r"); if(!file1){ getcwd(file_dir,1000); strcat(file_dir,"/a.txt"); file1=fopen(file_dir,"r"); } } else{ getcwd(file_dir,1000); strcat(file_dir,"/a.txt"); file1=fopen(file_dir,"r"); } //open file 2 if(args_num>=3){ getcwd(file_dir,1000); strcat(file_dir,"/"); strcat(file_dir,args[2]); file2=fopen(file_dir,"r"); if(!file2){ getcwd(file_dir,1000); strcat(file_dir,"/b.txt"); file2=fopen(file_dir,"r"); } } else{ getcwd(file_dir,1000); strcat(file_dir,"/b.txt"); file2=fopen(file_dir,"r"); } //open file 3 and 4 if(args_num==4){ getcwd(file_dir,1000); strcat(file_dir,"/"); strcat(file_dir,output); strcat(file_dir,"_1"); file3=fopen(file_dir,"w"); getcwd(file_dir,1000); strcat(file_dir,"/"); strcat(file_dir,output); strcat(file_dir,"_2"); file4 = fopen(file_dir,"w"); if(!file3 || !file4){ getcwd(file_dir,1000); strcat(file_dir,"/c_1.out"); file3=fopen(file_dir,"w"); getcwd(file_dir,1000); strcat(file_dir,"/c_2.out"); file4=fopen(file_dir,"w"); } } else{ getcwd(file_dir,1000); strcat(file_dir,"/c_1.out"); file3=fopen(file_dir,"w"); getcwd(file_dir,1000); strcat(file_dir,"/c_2.out"); file4=fopen(file_dir,"w"); } if(!file1 || !file2){ printf("Error in input files.\n"); exit(0); } //read file 1 read_file1(file1); //read file 2 read_file2(file2); // check for multiplication condition if(m1!=n2){ printf("m1 does not equal n2, can not do multiplication.\n"); exit(0); } //allocate matrix3 and matrix4 matrix_allocate(&matrix3,n1,m2); //method 1 int i,j; pthread_t threads[n1][m2]; clock_t start=clock(); int flag1=1,flag2=1; for(i=0;i<n1;i++){ int return_code= pthread_create(&threads[i][0],NULL,method1,(void *)i); if(return_code){ //error occured creating thread flag1=0; break; } } //join threads to continue with method2 int k; for(k=0;k<i;k++){ pthread_join(threads[k][0],NULL); } //output1 if(flag1){ clock_t mthd1=clock(); printf("Method 1\n"); printf("Number of threads = %d\n",n1); printf("Execution time = %lf milliseconds\n",(double) (mthd1-start)/CLOCKS_PER_SEC*1000.0); write_file(file3); } else printf("Error occured in method 1.\n"); //initialize matrix3 for(i=0;i<n1;i++){ for(j=0;j<m2;j++) matrix3[i][j]=0; } //method 2 clock_t start2 = clock(); for(i=0;i<n1;i++){ for(j=0;j<m2;j++){ int return_code= pthread_create(&threads[i][j],NULL,method2,(void *)(i*m2+j)); if(return_code){ flag2=0; break; } } } int w; for(w=0;w<i;w++){ for(k=0;k<j;k++){ pthread_join(threads[w][k],NULL); } } //output 2 if(flag2){ clock_t mthd2=clock(); printf("Method 2\n"); printf("Number of threads = %d\n",n1*m2); printf("Execution time = %lf milliseconds\n",(double)(mthd2-start2)/CLOCKS_PER_SEC*1000.0); write_file(file4); } else printf("Error occured in method 2.\n"); //close files fclose(file1); fclose(file2); fclose(file3); fclose(file4); return 0; }