# Matrix product simple case

Hi,

I am new to sage and I was trying to write a short program for matrix multiplication .

here is my program

def Produit(A,B):
n=A.nrows()
C=matrix(n,n)
for i in [0..n-1]:
for j in [0..n-1]:
for k in [0..n-1]:
C[i,j]=C[i,j]+A[i,k]*B[k,j]
return C


When I try to ran it , I receive an error message

TypeError: no conversion of this rational to integer

edit retag close merge delete

Please provide more information: first, what version of Sage? Second, what matrices A and B did you use?

( 2023-11-03 23:48:16 +0200 )edit

SageMath 9.3

I used the command random_matrix to create A and B.

A=random_matrix(QQ,2^5,2^5) B=random_matrix(QQ,2^5,2^5)

( 2023-11-04 07:13:53 +0200 )edit

Sort by ยป oldest newest most voted

Please try C=matrix(QQ,n,n).

more

Le'ts runn this by hand

sage: A=random_matrix(QQ,2^5,2^5)
sage: B=random_matrix(QQ,2^5,2^5)


Note that

sage: A.parent()
Full MatrixSpace of 32 by 32 dense matrices over Rational Field

sage: n=A.nrows()
sage: C=matrix(n,n)


Note that

sage: C.parent() Full MatrixSpace of 32 by 32 dense matrices over Integer Ring

So all elements of C are defined as integers. But this cannot be satisfied if any of the elements of A*B cannoit be coerced to an integer. In our case (and using Sage's matrix product to be a bit faster) :

sage: any(map(lambda u:not(u.is_integer()), (A*B).list()))
True


There you have it : at least one element of AB is not an integer. Note that *some elements of A*B might be integers :

sage: any(map(lambda u:u.is_integer(), (A*B).list()))
True


A (relativelty) fixed version of your function might be :

def Produit(A,B):
""" Product of two matrices A and B
Works if and only if A and B have the same parent"""
n=A.nrows()
C=matrix(A.parent(), n,n)
for i in [0..n-1]:
for j in [0..n-1]:
for k in [0..n-1]:
C[i,j]=C[i,j]+A[i,k]*B[k,j]
return C


HTH,

more