eigenmath/trace.cpp

78 lines
981 B
C++
Raw Permalink Normal View History

2004-03-03 21:24:06 +01:00
// Compute the trace of a matrix (sum of diagonal elements)
2005-06-30 17:54:52 +02:00
#include "stdafx.h"
2004-03-03 21:24:06 +01:00
#include "defs.h"
2005-06-30 17:54:52 +02:00
static void ytrace(void);
2004-03-03 21:24:06 +01:00
void
eval_trace(void)
{
push(cadr(p1));
eval();
trace();
}
void
trace(void)
{
save();
2005-06-30 17:54:52 +02:00
ytrace();
2004-03-03 21:24:06 +01:00
restore();
}
static void
2005-06-30 17:54:52 +02:00
ytrace(void)
2004-03-03 21:24:06 +01:00
{
2005-06-30 17:54:52 +02:00
int i, n;
2004-03-03 21:24:06 +01:00
p1 = pop();
// trace of scalar is ok even though contract(scalar) is not
if (isnum(p1)) {
push(p1);
return;
}
if (!istensor(p1)) {
push_symbol(TRACE);
push(p1);
list(2);
return;
}
if (p1->u.tensor->ndim != 2 || p1->u.tensor->dim[0] != p1->u.tensor->dim[1])
stop("trace(m): m is not a square matrix");
n = p1->u.tensor->dim[0];
2005-06-30 17:54:52 +02:00
for (i = 0; i < n; i++)
2004-03-03 21:24:06 +01:00
push(p1->u.tensor->elem[n * i + i]);
2005-06-30 17:54:52 +02:00
2006-08-23 16:42:43 +02:00
add_all(n);
2004-03-03 21:24:06 +01:00
}
static char *s[] = {
"trace(A)",
"trace(A)",
"trace(0)",
"0",
"trace(1)",
"1",
"trace(((a,b),(c,d)))",
"a+d",
"trace((a,b))",
2004-09-01 16:55:03 +02:00
"Stop: trace(m): m is not a square matrix",
2004-03-03 21:24:06 +01:00
};
void
test_trace(void)
{
test(__FILE__, s, sizeof s / sizeof (char *));
}