innerProd.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. RES = innerProd(MAT);
  3. Computes mat'*mat
  4. Odelia Schwartz, 8/97.
  5. */
  6. #define V4_COMPAT
  7. #include <matrix.h>
  8. #include <stdio.h>
  9. #include <ctype.h>
  10. #include <math.h>
  11. #include <strings.h>
  12. #include <stdlib.h>
  13. void mexFunction(int nlhs, /* Num return vals on lhs */
  14. mxArray *plhs[], /* Matrices on lhs */
  15. int nrhs, /* Num args on rhs */
  16. const mxArray *prhs[] /* Matrices on rhs */
  17. )
  18. {
  19. register double *res, *mat, tmp;
  20. register int len, wid, i, k, j, jlen, ilen, imat, jmat;
  21. mxArray *arg;
  22. /* get matrix input argument */
  23. /* should be matrix in which num rows >= num columns */
  24. arg=prhs[0];
  25. mat= mxGetPr(arg);
  26. len = (int) mxGetM(arg);
  27. wid = (int) mxGetN(arg);
  28. if ( wid > len )
  29. printf("innerProd: Warning: width %d is greater than length %d.\n",wid,len);
  30. plhs[0] = (mxArray *) mxCreateDoubleMatrix(wid,wid,mxREAL);
  31. if (plhs[0] == NULL)
  32. mexErrMsgTxt(sprintf("Error allocating %dx%d result matrix",wid,wid));
  33. res = mxGetPr(plhs[0]);
  34. for(i=0, ilen=0; i<wid; i++, ilen+=len)
  35. {
  36. for(j=i, jlen=ilen; j<wid; j++, jlen+=len)
  37. {
  38. tmp = 0.0;
  39. for(k=0, imat=ilen, jmat=jlen; k<len; k++, imat++, jmat++)
  40. tmp += mat[imat]*mat[jmat];
  41. res[i*wid+j] = tmp;
  42. res[j*wid+i] = tmp;
  43. }
  44. }
  45. return;
  46. }