1 /* matexpo.c 2011-06-23 */
3 /* Copyright 2007-2011 Emmanuel Paradis
5 /* This file is part of the R-package `ape'. */
6 /* See the file ../COPYING for licensing issues. */
9 #include <R_ext/Lapack.h>
11 void mat_expo(double *P, int *nr)
12 /* This function computes the exponential of a nr x nr matrix */
14 double *U, *vl, *WR, *Uinv, *WI, *work;
15 int i, j, k, l, info, *ipiv, n = *nr, nc = n*n, lw = nc << 1;
16 char yes = 'V', no = 'N';
18 U = (double *)R_alloc(nc, sizeof(double));
19 vl = (double *)R_alloc(n, sizeof(double));
20 WR = (double *)R_alloc(n, sizeof(double));
21 Uinv = (double *)R_alloc(nc, sizeof(double));
22 WI = (double *)R_alloc(n, sizeof(double));
23 work = (double *)R_alloc(lw, sizeof(double));
25 ipiv = (int *)R_alloc(nc, sizeof(int));
27 /* The matrix is not symmetric, so we use 'dgeev'.
28 We take the real part of the eigenvalues -> WR
29 and the right eigenvectors (vr) -> U */
30 F77_CALL(dgeev)(&no, &yes, &n, P, &n, WR, WI, vl, &n,
31 U, &n, work, &lw, &info);
33 /* It is not necessary to sort the eigenvalues...
35 memcpy(P, U, nc*sizeof(double));
37 /* For the inversion, we first make Uinv an identity matrix */
38 memset(Uinv, 0, nc*sizeof(double));
39 for (i = 0; i < nc; i += n + 1) Uinv[i] = 1;
41 /* The matrix is not symmetric, so we use 'dgesv'.
42 This subroutine puts the result in Uinv (B)
43 (P [= U] is erased) */
44 F77_CALL(dgesv)(&n, &n, P, &n, ipiv, Uinv, &n, &info);
46 /* The matrix product of U with the eigenvalues diagonal matrix: */
47 for (i = 0; i < n; i++)
48 for (j = 0; j < n; j++)
49 U[j + i*n] *= exp(WR[i]);
51 /* The second matrix product with U^-1 */
52 memset(P, 0, nc*sizeof(double));
54 for (k = 0; k < n; k++) {
55 for (l = 0; l < n; l++) {
57 for (i = 0 + n*k, j = l; j < nc; i++, j += n)
58 P[lw] += U[j]*Uinv[i];