Welcome to Cadabra Q&A, where you can ask questions and receive answers from other members of the community.
+1 vote

Seasons greetings cdb experts, and many thanks in advance!

In the code below I first create the set of matrices Kl, then try to pick out the components of one of the matrices (K1 in the example) and display them.

My actual goal is to display a matrix with the right values in a nice LaTeX format.

If you run the code below, you will notice that I try to change the i,j element of a matrix but despite the element.replace(), the final TheK1Matrix has values {12, 21} and not values {1, -1}. My questions are:

  1. How to set the i,j element of the matrix below?
from cdb.core.component import *
from  cdb.utils.node import *

{k,l,m,n}::Indices(rotation, values={1,2,3}).
\epsilon{#}::EpsilonTensor.
Kl := (K_{l})_{m n} = \epsilon_{l m n};
evaluate(Kl, rhsonly=True);

TheK1Matrix := [[0,0,0],[0,0,12],[0,21,0],].
for ex in Kl[r'\equals']:
    lhs = get_lhs(ex.ex())
    rhs = get_rhs(ex.ex())
    if ${a?,b?,c?}$.matches(lhs):
        n = int(str(nth_arg(lhs,0)))
        if n == 1:
            i = int(str(nth_arg(lhs,1)))
            j = int(str(nth_arg(lhs,2)))
            for element in TheK1Matrix[i-1][j-1]:
                element;
                rhs;
                element.replace(rhs);
TheK1Matrix;
  1. Ultimately, my goal is to display that matrix using "nice" LaTeX formatting, of the general form
\begin{array}
    0 & 0 & 0 \\
    0 & 0 & 1 \\
    0 & -1 & 0
\end{array}

How to achieve that?

Thank you

GPN

in General questions by (2.0k points)
edited by

1 Answer

+1 vote
 
Best answer

Some answers I gathered in the hope they help others.

Answer #1:

The following code isn't pretty, but it solves issue #1 by creating a python matrix and storing values into that matrix..

from cdb.core.component import *
from  cdb.utils.node import *

d = 3
{k,l,m,n}::Indices(rotation, values={1..3}).
\epsilon{#}::EpsilonTensor.
Kl := (K_{l})_{m n} = \epsilon_{l m n};
evaluate(Kl, rhsonly=True);

mat = [[0 for _ in range(d)] for _ in range(d)]
for ex in Kl[r'\equals']:
    lhs = get_lhs(ex.ex())
    rhs = get_rhs(ex.ex())
    if ${a?,b?,c?}$.matches(lhs):
        n = int(str(nth_arg(lhs,0)))
        if n == 1:
            i = int(str(nth_arg(lhs,1)))
            j = int(str(nth_arg(lhs,2)))
            mat[i-1][j-1] = str(rhs)

After this, depending on your use case, you can, e.g. turn the matrix into a string and display the string in a LaTeX format, as follows.

Answer #2: beginning in version 2.4.5.2, the following (using the new feature LaTeXString) works:

K1 = r'\left[ \begin{array}{cc} '
for i in range(d):
    for j in range(d):
        if j%d > 0: K1 += ' & '
        K1 += str(mat[i][j])
    if i%d < d-1: K1 += r' \\'
    K1 += r' '
else:
    K1 += r'\end{array} \right]'

LaTeXString(K1);

Good luck

by (2.0k points)
edited by
...