Ask Your Question
0

Matrix product simple case

asked 2023-11-03 11:03:16 +0100

kiki gravatar image

updated 2023-11-03 23:46:38 +0100

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 flag offensive close merge delete

Comments

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

John Palmieri gravatar imageJohn Palmieri ( 2023-11-03 23:48:16 +0100 )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)

kiki gravatar imagekiki ( 2023-11-04 07:13:53 +0100 )edit

2 Answers

Sort by ยป oldest newest most voted
0

answered 2023-11-04 07:33:34 +0100

Emmanuel Charpentier gravatar image

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,

edit flag offensive delete link more
0

answered 2023-11-04 07:26:27 +0100

tolga gravatar image

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

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2023-11-03 11:03:16 +0100

Seen: 97 times

Last updated: Nov 04 '23