eigenmath/cofactor.cpp

67 lines
1.1 KiB
C++
Raw Permalink Normal View History

2006-01-06 18:26:49 +01:00
// Cofactor of a matrix component.
2006-01-06 04:13:23 +01:00
#include "stdafx.h"
#include "defs.h"
void
eval_cofactor(void)
{
int i, j, n;
2006-01-06 18:26:49 +01:00
push(cadr(p1));
2006-01-06 04:13:23 +01:00
eval();
p2 = pop();
if (istensor(p2) && p2->u.tensor->ndim == 2 && p2->u.tensor->dim[0] == p2->u.tensor->dim[1])
;
else
stop("cofactor: 1st arg: square matrix expected");
n = p2->u.tensor->dim[0];
2006-01-06 18:26:49 +01:00
push(caddr(p1));
2006-01-06 04:13:23 +01:00
eval();
i = pop_integer();
2006-01-06 18:26:49 +01:00
if (i < 1 || i > n)
stop("cofactor: 2nd arg: row index expected");
push(cadddr(p1));
2006-01-06 04:13:23 +01:00
eval();
j = pop_integer();
2006-01-06 18:26:49 +01:00
if (j < 1 || j > n)
stop("cofactor: 3rd arg: column index expected");
cofactor(p2, n, i - 1, j - 1);
2006-01-06 04:13:23 +01:00
}
void
cofactor(U *p, int n, int row, int col)
{
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (i != row && j != col)
push(p->u.tensor->elem[n * i + j]);
determinant(n - 1);
if ((row + col) % 2)
negate();
}
2006-01-06 18:26:49 +01:00
static char *s[] = {
"cofactor(((1,2),(3,4)),1,1)",
"4",
"cofactor(((1,2),(3,4)),1,2)",
"-3",
"cofactor(((1,2),(3,4)),2,1)",
"-2",
"cofactor(((1,2),(3,4)),2,2)",
"1",
"cofactor(((1,2,3),(4,5,6),(7,8,9)),1,2)",
"6",
};
void
test_cofactor(void)
{
test(__FILE__, s, sizeof s / sizeof (char *));
}