Reputation: 524
I am using sagemath for my computations.
Now, from R I have the codes to generate a matrix of size $2r\times 2r$ from the following codes..
n=10
k=10
r=5
x=matrix(data=NA, nrow=n, ncol=k)
for(j in 1:k){
for(i in 1:n){
if (i==j){x[i,j]=0}
if ((i<=r)&(i<j)&(j<=r)) {x[i,j]=2}
if ((i<=r)&(i>j)&(j<=r)) {x[i,j]=2}
if ((i<=r)&(j>r)){x[i,j]=1}
if ((i>r)&(j<=r)) {x[i,j]=1}
if ((i>r)&(j>r)){x[i,j]=0}
if ((i>r)& (i<j) &(j>r)){x[i,j]=2}
if ((i>r)& (i>j) &(j>r)){x[i,j]=2}
}
}
x
How can I do the same in SageMath?
Upvotes: 0
Views: 1018
Reputation:
When constructing a matrix in Sagemath, you can pass in a function that computes its entries, which eliminates the need for explicit (and generally inefficient) loops. This function is defined below as xentries
: I used the same conditionals as in your post, but grouped them for readability.
def xentries(i, j, r):
if i == j or (i > r and j > r):
return 0
if (i <= r and j > r) or (i > r and j <= r):
return 1
return 2
n = 10
k = 10
r = 5
x = matrix(ZZ, n, k, lambda i, j: xentries(i, j, r))
Here, ZZ means the integers, and is used to indicate that the matrix has integer entries. It could be rational QQ or real RR. The other arguments are the size of the matrix, and the function that constructs its entries. The matrix x is now the following:
[0 2 2 2 2 2 1 1 1 1]
[2 0 2 2 2 2 1 1 1 1]
[2 2 0 2 2 2 1 1 1 1]
[2 2 2 0 2 2 1 1 1 1]
[2 2 2 2 0 2 1 1 1 1]
[2 2 2 2 2 0 1 1 1 1]
[1 1 1 1 1 1 0 0 0 0]
[1 1 1 1 1 1 0 0 0 0]
[1 1 1 1 1 1 0 0 0 0]
[1 1 1 1 1 1 0 0 0 0]
Upvotes: 2