Creating Square Matrices Program

Question:

i need to create a Square Matrices Function.

DESCRIPTION:

Write a function that accepts two square (NxN) matrices (two dimensional arrays), and returns the product of the two. Only square matrices will be given.

How to multiply two square matrices:

We are given two matrices, A and B, of size 2×2 (note: tests are not limited to 2×2). Matrix C, the solution, will be equal to the product of A and B. To fill in cell [0][0] of matrix C, you need to compute: A[0][0] * B[0][0] + A[0][1] * B[1][0].

More general: To fill in cell [n][m] of matrix C, you need to first multiply the elements in the nth row of matrix A by the elements in the mth column of matrix B, then take the sum of all those products. This will give you the value for cell [m][n] in matrix C.

Here’s the question: https://www.codewars.com/kata/5263a84ffcadb968b6000513

Please when you give me a answer , give explanation as best as you can to understand well what are you doing this is a little bit hard for me.

I did this but i coudn’t go further because i didn’t know how to do.I wanted to do first element from a[0] which is 1 to mutiply to b[0]-3 and b[1]-2 and further more just read the question if you don’t understand what i’am talking

def matrix_mult(a, b):
    
    for row in a:
        for element in row:
            print(element)
    for row in b:
        for element in row:
            print(element)
Asked By: Joelinton

||

Answers:

The function matrix_mult() should work with most matrices. It is slow compared to NumPy or other python math libraries when it comes to large matrices.

# 3x3 matrix
a = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
# 3x4 matrix
b = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1],]

def matrix_mult(X, Y):
    # check if the dimensions of the matrices are compatible for multiplication
    if len(X[0]) != len(Y):
        print('Dimensions are incompatible.')
        return []
    
    # make an empty matrix with the right size
    result = [
        [0 for row in range(len(Y[0]))]
        for y in range(len(X))]
    
    for i in range(len(X)):  # iterate through rows of X
        for j in range(len(Y[0])):  # iterate through columns of Y
            # print(f'grid {i, j}')
            for k in range(len(Y)):  # iterate through rows of Y
                # print(f'{result[i][j]} += {X[i][k]} * {Y[k][j]}')
                result[i][j] += X[i][k] * Y[k][j]
            # print(f'Rectangle final value: {result[i][j]}')
    return result

Note: You can uncomment the print methods to get a little run-down of the function as it runs.

Answered By: Zack Walton
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.