user8314628
user8314628

Reputation: 2042

Python how to multiply non square matrices?

Suppose A is a MxN matrix. I want to multiply A with its transpose. Is it possible to do it with pure nested loop (i.e., not using np.transpose)? When I try to loop through it, I don't know how to figure out the range issue since the shape of the result is different from A.

Say A is 3x4. Then the result of A*(A^T) will be 3x3. Both of i, j in result[i][j] cannot be larger than 4. So how can I iterate by rows and columns?

Upvotes: 0

Views: 1785

Answers (4)

kaya3
kaya3

Reputation: 51034

Here's a solution using list comprehensions and sum:

a = [[1, 2], [3, 4], [5, 6]]

result = [
    [ sum(x*y for x, y in zip(row1, row2)) for row2 in a ]
    for row1 in a
]

# result = [[5, 11, 17], [11, 25, 39], [17, 39, 61]]

It works because each element in the matrix product of A and Aᵀ is the product of a row from A with a column from Aᵀ, and the columns of Aᵀ are just the rows of A.

Upvotes: 0

Anatoliy R
Anatoliy R

Reputation: 1789

Try this. No numpy, regular list and transferable to any language

for i in range(len(A)):
    for j in range(len(A)):
        # R must be initialized above with the proper shape (n x n)!
        R[i][j] = 0
        for k in range(len(A[0])):
            R[i][j] += A[i][k] * A[j][k]

Upvotes: 1

Richard Nemeth
Richard Nemeth

Reputation: 1864

It should very well be possible, by direct usage of matrix multiplication definition and standard numpy broadcasting:

import numpy as np

def matrix_multiplication_nested_loop(A, B):
    res = np.zeros((A.shape[0], B.shape[1]))

    for _x in range(A.shape[0]):
        for _y in range(B.shape[1]):
            res[_x, _y] = np.sum(A[_x, :] * B[:, _y])
    return res

A = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [0, 1, 2, 1]])
B = np.array([[1, 5, 0], [2, 6, 1], [3, 7, 2], [4, 8, 1]]) # A.T

Upvotes: 0

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

Yes, it is possible, you can try this if you want to rely purely on nesting.

x = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

result = []
for k in range(len(x)):
    temp = []
    for i in range(len(x)):
        tempSum = 0
        for j in range(len(x[0])):
            tempSum += x[k][j]*x[i][j]
        temp.append(tempSum)
    result.append(temp)

print(result)

Output:

[[14, 38, 62], [38, 126, 214], [62, 214, 366]]

you can verify it with numpy:

>>> x = np.arange(12).reshape(3,4)
>>> [email protected]

array([[ 14,  38,  62],
       [ 38, 126, 214],
       [ 62, 214, 366]])

Upvotes: 1

Related Questions