1

In Sage, trying to define a matrix with conditions for the cells by:

matrix([[(if gcd(i, j) == 0: log(radical((i+j)*i*j)) else: -1.0) for j in srange(1, 5)] for i in srange(1, 5)])

I get a syntax error:

...
matrix([[(if gcd(i, j) == _sage_const_0 : log(radical((i+j)*i*j)) else: -_sage_const_1p0 ) for j in srange(_sage_const_1 , _sage_const_5 )] for i in srange(_sage_const_1 , _sage_const_5 )])
           ^
SyntaxError: invalid syntax

What is the problem here? How to fix that?

Samuel Lelièvre
  • 3,212
  • 1
  • 14
  • 27

2 Answers2

2

Your problem is a Python one, really, not Sage per se. Python has some filtering for list comprehensions, but it doesn't look like this. See e.g. this question.

So let's try it:

matrix([[log(radical((i+j)*i*j)) if gcd(i,j)==0 else -1.0 for j in srange(1,5)] for i in srange(1,5)])

By the way, did you really want if gcd(i,j)==1? Unlikely you'll get a gcd of zero in this one!

Community
  • 1
  • 1
kcrisman
  • 4,374
  • 20
  • 41
1

Here is another possibility.

sage: f = lambda i, j: log(radical((i + j)*i*j)) if gcd(i,j) == 1 else -1
sage: m = matrix(SR, 4, lambda i, j: f(i + 1, j + 1))
sage: m
[ log(2)  log(6)  log(6) log(10)]
[ log(6)      -1 log(30)      -1]
[ log(6) log(30)      -1 log(42)]
[log(10)      -1 log(42)      -1]

This uses a different syntax for matrix initialization, in which we first specify the base ring, the matrix size, and then a function of (i, j) for coefficients. Note that since Sage indexes rows and columns from 0, we have to apply our function to i + 1 and j + 1.

Putting -1 for non-coprime (i, j) might work better than -1.0 for exact computations.

Samuel Lelièvre
  • 3,212
  • 1
  • 14
  • 27