Matrix multiplication in python program

Matrix multiplication in python program. multiply() :-This function is used to perform element wise matrix multiplication. Let’s say we want to multiply matrix A with matrix B to compute matrix C. Like above, here we have done the same thing but the slight difference is we multiplied a scaler value to an array. Input: p[] = {40, 20, 30, 10, 30} Output: 26000. mult_mat(M, 2) will give M * M, therefore, mult_mat(M, 1) just returns M itself. Jan 16, 2024 · 4. dot () We can use NumPy’s dot() function to multiply two matrices. Each element in the matrix is multiplied by the scalar, which makes the output the same shape as the original matrix. mat(result) edited Dec 26, 2017 at 16:42. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. matmul(a, b) array([16, 6, 8]) numpy. We can use for loops In this tutorial, you will learn about the python program for matrix multiplication by getting input from user. We can perform a modulus operation in NumPy arrays using the % operator or the mod() function. It's only suitable for tensors of rank 2 (matrices) and doesn't support broadcasting like torch. Python’s matrix multiplication: Tackling big data with Sep 26, 2020 · The first step, before doing any matrix multiplication is to check if this operation between the two matrices is actually possible. Following program has two matrices x and y each with 3 rows and 3 columns. a = np. Oct 7, 2019 · Output: This output represents the product of the given matrices A and B. Algorithm Step1: input two matrix. Apr 2, 2020 · Basics. Create a new 2D list result using a nested list comprehension. I have a block of code that takes user input and creates them into matrices but i need them to run in parallel as appose to running the code as one single process. First take a remainder or individual number like arr [i] % n. of columns in matrix 1 = no. Rows of the 1st matrix with columns of the 2nd; Example 1. It has two rows and 2 columns. In python, we can define our own functions. dot() method is used to find out the dot product of two matrices. Code: Python code explaining Scalar Multiplication. It can deal with only two-dimensional matrices and not with single-dimensional ones. In the above image, 19 in the (0,0) index of the outputted matrix is the dot product of the 1st row of the 1st matrix and the 1st column of the 2nd matrix. May 9, 2023 · 1. Apr 2, 2024 · This operator is a convenient way to perform matrix multiplication, but it has limitations. dot function because now i must distinguish the 1d vector and matrix. A location into which the result is stored. dot(result_pre_tilt). Examples: Input : X = [[1, 7, 3], [3, 5, 6], [6, 8, 9]] Y = [[1, 1, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] . sys. shape != x2. C Multidimensional Arrays. Python for loops allow us to iterate over over iterable objects, such as lists. This guide will explore matrix multiplication in Python, including various techniques and tools for performing this In this Python matrix multiplication method, we will utilize a nested for loop on two matrices to execute multiplication on them and store the result of the multiplication in the third matrix as the result value. Jul 28, 2023 · Python program to multiply two matrices - GeeksforGeeks. Dec 20, 2022 · Multiplication of matrix does take time surely. Mar 2, 2020 · Python Server Side Programming Programming. A mxn x B pxq then n should be equal to p. Nov 30, 2017 · When I had to do some matrix arithmetic I defined a new class to help. Matrix Multiplication In Python using Function | Here, we will discuss how to multiply two matrices in Python using function. Here are some key considerations to keep in mind: Vectorization: Utilize vectorized operations provided by libraries like NumPy to take advantage of optimized code for matrix multiplication. It first determines the number of rows and columns of the matrices using the len() function. Matrix Multiplication between two matrices A and B is legitimate provided that the variety of columns in mildew a is equal to the variety of rows in mildew B. dot() # 3 x 3 matrix. I've got it working somewhat. dot() function to perform matrix multiplication. Avoid such confusion of names by putting the main logic also in a function, so that its A and B are also local. May 31, 2022 · Given a sequence of matrices, find the most efficient way to multiply these matrices together. Below is the Python code given: 1. Broadcasting is nothing but the way the Tensors are treated when their shapes are different. NumPy arrays offer efficient and convenient tools for performing various matrix operations. In R, you can perform matrix multiplication using a for loop by iterating over the Jan 13, 2023 · Python program that uses nested loops to multiply two matrices: The function multiply_matrices(A, B) takes two 2D matrices A and B as arguments. 4. stdin First we need to import sys module. matmul. Here we see that by using dynamic programming programming approach, we reduce the cost of multiplication from 222 to 150. Below is the Python program to multiply two matrices using nested lists: Code. rslt[R1][C2] Below is the implementation of the multiplication of two matrices: C++ Here you will get program for python matrix multiplication. >>> np. stdininput()fileinput. Earlier than we write matrix multiplication Python code, let’s evaluation the fundamentals of matrix multiplication. Jan 22, 2021 · torch. This Python program specifies how to multiply two matrices having specific values. 5]] N=1. Feel free to run this Python program in your environment to observe the matrix multiplication output. Apr 20, 2023 · We need to write a function MatrixChainOrder () that should return the minimum number of multiplications needed to multiply the chain. This function does not support broadcasting. In Tensorflow, it’s equivalent to the matmul function from the Here are few more examples related to Python matrices using nested lists. There are a number of ways in which we can take input from stdin in Python. Given two matrices, the task to multiply them. 5. Then it creates a new 2D matrix C with rows of the first matrix and columns of the second matrix and all Apr 28, 2011 · This is continued from thread: Python array multiply. {7, 7}} Input : mat1[][] = {{2, 4}, . In addition to NumPy and SymPy, for example, TensorFlow also implements this operator. The columns, i. Let’s replicate the result in Python. Output of multiplication of Matrix-1 and Matrix-2, results with equal to the number of rows of Matrix-1 and the number of columns of Matrix-2 i. res[i][j] += m1[i][k] * m2[k][j] for r in res: print(r) Output:-. Then only we can multiply matrices. From previous thread, I learned how to multiply . Note- Matrix multiplication is only possible when Number of columns in matrix 1 is equal to the number of rows in matrix 2. # Program to multiply two matrices using np. Our task is to display the addition of two matrix. One of the major needed steps in linear algebra is scalar multiplication. The matrix is referred to as an m by n matrix, denoted by the symbol “m x n” if there are m rows Sep 2, 2020 · Vector multiplication is of three types: Scalar Product Dot Product Cross Product Scalar Multiplication: Scalar multiplication can be represented by multiplying a scalar quantity by all the elements in the vector matrix. Before writing the Python program, let's first look at the overview of the multiplication of two matrices. start = timeit. Syntax: numpy. Hope this was useful. shape[1] == B. Experience seamless matrix multiplication – your gateway to optimized programming excellence. Multiply Two Python Lists by a Number Using a For Loop. The inner most Recursive call of multiplyMatrix() is to iterate k (col1 or row2). Multi-threading can be done to improve Matrix multiplication using nested lists The zip is used. Code. People are also reading: Python Program to Display Calendar WAP to find the Sum of Series 1/2+4/5+7/8+… In this tutorial, you will learn about the python program for matrix multiplication by getting input from user. If not provided or None, a freshly-allocated Apr 25, 2023 · Let's discuss how to find the inner, outer, and cross products of matrices and vectors using NumPy in Python. from numba import njit, prange. Here's my code: matrix = [[0 for row in range(p)] for col in range(q)] return matrix. array([2, 5, 7]) # using the % operator. May 20, 2020 · Matrix is the key to linear algebra. Feb 20, 2014 · In numerical code, there are two important operations which compete for use of Python’s * operator: elementwise multiplication, and matrix multiplication. array(a) returns a 2D array of type ndarray and multiplication of two ndarray would result element wise multiplication. Feb 3, 2021 · You can use numba, which will compile your function and make it really fast. This works because of distributive properties of modular numpy. And, the element in the first-row first column can be selected as X[0][0]. dot with two major exceptions: no scalar multiplication but it works with stacks of matrices. Element-wise Multiplication. If provided, it must have a shape that the inputs broadcast to. x and y are the two matrices you're multiplying together, which you store in result. I'm trying to implement Strassen Matrix multiplication in Python. The multiplication_table () function is defined, which takes a parameter number representing the input number for the multiplication table. import numpy as np. The program below asks for the number of rows and columns of two matrices until the above condition is satisfied. Mar 15, 2013 · Strassen's algorithm for matrix multiplication only works for 2^n-by-2^n matrices. {3, 4}} mat2[][] = {{1, 2}, . array([1,2,3,4]) sc= 13. Dec 7, 2023 · Using recursive function. I don't want to use "numpy". Dec 21, 2020 · In this method, dot() method of numpy is used. The value stored in the product at the end will give you your final answer. So the result would be: result = [[5, 12], [21, 32]] If you wanna get a matrix, the do it with this: result = np. 2. Dec 24, 2023 · The Code. It will repeat the string the number of times specified by the integer. In the inner list comprehension, iterate through the rows of A and extract the ith element from each row. Introduction Matrix multiplication is a fundamental operation in linear algebra, used in various fields such as physics, engineering, computer graphics, and machine learning. import math. Mar 1, 2023 · Program for multiplication of array elements. Python Program to Multiply Two Matrices using For Loop. In Python, use the asterisk “*” operator to multiply a string with an integer. Examples: Input : mat1[][] = {{1, 2}, . We can also combine some matrix operations together to perform complex calculations. import matplotlib. The time complexity taken by this approach is O (n3), since it takes two loops to. bmm (batch matrix multiplication) and operates on the last two dimensions of the tensors. Created Date: Oct 25, 2023 · In this example, we will multiply an array to a scaler value using numpy. In scalar multiplication, we multiply a scalar by a matrix. #. Multiply all numbers in the list using Traversal. This tutorial provides a step-by-step guide to writing a program to multiply two matrices with examples. We will learn about the programming logic and concept of Python matrix multiplication and various methods. This program asks the user to enter the size (rows and columns) of two matrices. In this section, you’ll learn how to use a Python for loop to multiply a list by a number. In Numpy, number of dimensions of the array is called rank of the array. Time complexity of matrix multiplication is O(n^3) using normal matrix multiplication. Matrix multiplication with Python. Let’s look at an example: import numpy as np. For the above code, we have given our own set of values, then we have initialized the resultant matrix res to 0 and Jul 14, 2016 · I have 3, 3X3 matrices stored in numpy arrays. Nov 2, 2013 · Hi Everyone I am python newbie I have to implement lasso L1 regression for a class assignment. The np. The main aim for this is to reuse the code hence it reduces the number of lines. Matrix Multiplication in Python Using numpy. dot for matrix-vector multiplication but behaves differently for matrix Dec 22, 2023 · In Recursive Matrix Multiplication, we implement three loops of Iteration through recursive calls. Mar 27, 2024 · A simple form of matrix multiplication is scalar multiplication, you can do that by using the NumPy dot() function. result = np. To multiply two matrices, the number of columns of the first matrix should be equal to the number of rows of the second matrix. We have to pass two matrices in this method for which we have required dot product. In the fields of engineering, physics, statistics, and graphics, matrices are widely used to express picture rotations and other types of transformations. It works for 4-by-4 because 4 is a power of 2. I hope that it will be possible to just call simple . import timeit. Output : [55, 65, 49, 5] [57, 68, 72, 12] See full list on geekflare. In Python, you can perform matrix multiplication efficiently using different methods and libraries. Jan 11, 2024 · Unlock the power of python with our Matrix Multiplication program! Effortlessly perform complex matrix operations for enhanced computational efficiency. After multiplication, again take remainder to avoid overflow. inner functions the same way as numpy. Step 2) It shows a 2×3 matrix. It's equivalent to torch. The numpy. The row1 has values 2,3, and row2 has values 4,5. The data inside the matrix are numbers. To define a function we use the def keyword. Mar 7, 2024 · Multiplication tables are fundamental in mathematics, serving as the building blocks for more advanced concepts. In this article, we will explore some commonly used and straightforward methods to create multiplication tables using while loops. Syntax. ar = np. Python As of mid 2016 (numpy 1. In Python, we can use various methods to generate multiplication tables, and one versatile tool for this task is the ‘while’ loop. Elevate your coding skills with our easy-to-understand python solution. v = np. Within such a class you can define magic methods like __add__, or, in your use-case, __matmul__, allowing you to define x = a @ b or a @= b rather than matrixMult(a,b). multiply(ar, sc) result. This involves solving a quadratic equation involving block matrices. mul(a, b) print(c) Feb 6, 2023 · A matrix is a collection of numbers arranged in a rectangular array in rows and columns. May 15, 2024 · When implementing matrix multiplication in Python, it is essential to consider to ensure optimal performance, especially when dealing with large datasets. stdin can be used to get input from the command line directly. of rows in matrix 2 To multiply two matrices use the dot() function of NumPy. {3, 4}} mat2[][] = {{1, 1}, . This operation calculates the remainder of element-wise division between two arrays. dot(x,y) where x and y are two matrices of size a * M and M * b, respectively. The standard multiplication sign in Python * produces element-wise multiplication on NumPy arrays. answered Dec 26, 2017 at 5:32. Every m_c multiplied results need to get summed. @njit(parallel=True) def mat_mult(A, B): assert A. Jul 21, 2022 · Vector multiplication is of three types: Scalar Product Dot Product Cross Product Scalar Multiplication: Scalar multiplication can be represented by multiplying a scalar quantity by all the elements in the vector matrix. The second recursive call of multiplyMatrix() is to change the columns and the outermost recursive call is to change rows. Matrix multiplication involves multiplying the elements of rows in the first matrix by the corresponding elements of columns in the second matrix and summing the products to generate the elements of the resulting matrix. e. Now, let's look what happens for the first few multiplications. 5], [168. you can also use the @ operator to perform matrix multiplication, for example a @ b or a. Jul 30, 2019 · Python program multiplication of two matrix - Given two user input matrix. array([[1,2], [3,4]]) b = np. This loop variable i represents the values from 1 to 10. It takes only 2 arguments and returns the product of two matrices. inner() method impor Feb 21, 2023 · In this article, we will read How to take input from stdin in Python. Then multiply the remainder with current result. Oct 14, 2016 · Here, np. array([4, 1]) w = 5 * v. 10. if len(a[0]) != len(b): # if # of col != # of rows: return "Matrices are not m*n and n*p". The general syntax is : np. It inputs two matrices, A and B, and returns their product. mm (): This method computes matrix multiplication by taking an m×n Tensor and an n×p Tensor. In the multiplication, you have 3 matrices going on. The following code shows an example of multiplying matrices in NumPy: May 24, 2024 · Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. Code: Python code explaining Scalar Multiplication # importing libraries import numpy as np import matplotlib. else: Sep 26, 2020 · The first step, before doing any matrix multiplication is to check if this operation between the two matrices is actually possible. If you try to use Strassen's algorithm on matrices whose size is not a power of 2, at some point along the way you'll end up attempting to add or subtract two matrices that are not of the same shape, and that will either fail or give you the wrong answer. Also, it is very easy to include parallelization with threads: import numpy as np. In the nearly twenty years since the Numeric library was first proposed, there have been many attempts to resolve this tension [13] ; none have been really satisfactory. Matrix multiplication Feb 23, 2024 · This Python code defines a function matrix_multiply that uses NumPy's np. ”. This can be done by checking if the columns of the first matrix matches the shape of the rows in the second matrix. The library works really well with numpy. Aug 22, 2023 · The best way to verify if matrix multiplication is legitimate. The dimensions of A, B and C should be matched accordingly. Matrix multiplication involves the dot product of rows and columns, and NumPy simplifies this operation. Feb 28, 2023 · Read: Python program to print element in an array. {1, 1}} Output : {{3, 3}, . When a matrix is defined using NumPy, it's easy to code scalar multiplication. mul (b) Example of how to perform matrix multiplication in Python using NumPy: import numpy as np. 1), you can try the experimental numpy. In scalar multiplication, you can multiply a scalar by a matrix or multiply a matrix by a scalar. Initialize a 2D list A with the given matrix values. Strassen’s Matrix Multiplication - Strassen's Matrix Multiplication is the divide and conquer approach to solve the matrix multiplication problems. Array Multiplication. Jan 25, 2024 · In Python, matrices can be represented using nested lists or NumPy arrays. Matrix multiplication is Python Program For Multiplication Table. In the previous program, inputs are hardcoded in the program but in this program, we take user input to multiply two matrices using a list; we intake row values and column values from the user and then proceed with the elements. For example, if you want to multiply 3 matrices called A, B and C in that order, we can use np. Step 3: take one resultant matrix which is initially contains a. For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. NumPy array can be multiplied by each other using matrix multiplication. We can treat each element as a row of the matrix. Simple Python Program for Matrix Multiplication. Multiplication can be done using nested loops. multiply (). The usual matrix multiplication method multiplies each row with each column to achieve the product matrix. Append the extracted elements as a row to the result list. Matrices can either be square or rectangular. Every n_c summed Dec 12, 2021 · In the next section, you’ll learn how to use a Python for loop to multiply a list by a number. inner(arr1, arr2) Code : C/C++ Code # Python Program illustrating # numpy. Nested for loop is a for loop inside another for loop. default_timer() def getMatrix(name): matrixCreated = [] i = 0. How to multiply string with an integer in python. . We need to check this condition while implementing code without ignoring. We will write a Python program to get the multiplication of two input matrices and print the result in output. Every element in the matrix is multiplied by the scalar, which returns the same shape array as the original array. We are given an array, and we have to calculate the product of an array using both iterative and recursive methods. Last Updated : 28 Jul, 2023. input()Read Input From stdin in Python using sys. May 5, 2020 · Scalar Multiplication: Scalar multiplication can be represented by multiplying a scalar quantity by all the elements in the vector matrix. I want to get the product, to compute a rotation matrix. Multiplication of two matrices is possible only when number of columns in first matrix equals number of rows in second matrix. Below is Recursive Matrix Multiplication code. dot (A, B), C). Matrix multiplication. The transpose of a matrix is obtained by swapping its rows with columns. If x1. array([[5,6], [7,8]]) c = np. Jan 4, 2016 · You want to multiply a matrix, M, with itself. of rows in matrix 2 Oct 13, 2020 · 1. matmul, which works like numpy. Mar 24, 2021 · So, numpy is a powerful Python library. And Strassen algorithm improves it and its time complexity is O(n^(2. The first row can be selected as X[0]. com Feb 24, 2022 · Python Program to multiply two matrices - GeeksforGeeks. pyplot as plt. 0. multiply. shape[0] Jul 23, 2023 · You have a few errors: if len(A) == 1 and len(A[0]) == 1 references the global names A and B instead of the parameter names a and b (also in next statement). Nov 26, 2019 · The code for list comprehension version of matrix multiplication is more concise, and it also runs faster. split())) Jul 23, 2023 · You have a few errors: if len(A) == 1 and len(A[0]) == 1 references the global names A and B instead of the parameter names a and b (also in next statement). Assume A is a p × w matrix and B is a w × q matrix, So C will be p × q matrix. number*array: hh=[[82. May 20, 2024 · Matrix Multiplication is the product of two matrices that result in the formation of one matrix. 6 days ago · Scalar multiplication is a simple form of matrix multiplication. 8074)). Initialize the value of the product to 1 (not 0 as 0 multiplied with anything returns zero). Input arrays to be multiplied. # This code finds the remainder of the product of all the elements in the array arr divided by 'n'. rslt[R1][C2] Below is the implementation of the multiplication of two matrices: C++ Matrix Multiplication in Python Using List. Mar 22, 2023 · Program for scalar multiplication of a matrix; Program to find transpose of a matrix; C Program to Multiply two Floating Point Numbers; Java Program To Multiply Two Numbers Represented By Linked Lists; Python Program to Add Two Matrices; Java Program to Check the Multiplicability of Two Matrices; Python Program to Multiply Two Binary Numbers Jul 30, 2019 · Python program multiplication of two matrix - Given two user input matrix. I have no clue how to do so, i started reading into NumPy but haven't really grasped it. row = list(map(int, input(). Matrix multiplication is a binary operation that multiplies two matrices, as in addition and subtraction both the matrices should be of the same size, but here in multiplication matrices need not be of the same size. We Matrix Multiplication Program in Python | Here, we will discuss how to multiply two matrices in Python. Multiply arguments element-wise. Two matrices can only be multiplied if the number of columns of the first matrix is equal to the number of rows of the second matrix. /5 ll = [[x*N for x in y] for y in hh] But how can I multiply array*array:->matrix multiplication. If we want to multiple two matrices then it should satisfy one condition. To multiply a matrix we use a nested for loop. It is a binary operation performed on two matrices to get a new matrix called the product matrix. X = [[10, 3, 5], In the above code, matrix multiplication in python user input. This can be formulated as: → no. dot product is nothing but a simple matrix multiplication in Python using numpy library. Step 2: nested for loops to iterate through each row and each column. In this article, we will learn how to write a Python program that multiplies matrices based on user input. Python interpreter spots predictable patterns during looping making list comprehension Sep 24, 2022 · Given two matrices, the task is to write a program in Python and C++ to multiply the two matrices. Mar 19, 2024 · The number of columns in Matrix-1 must be equal to the number of rows in Matrix-2. Issue with numpy matrix Feb 21, 2024 · Matrix Multiplication using For loop in R. dot() function efficiently computes the dot product of two arrays, corresponding to matrix multiplication for 2D arrays. The result is printed to the console. dot() :- This function is used to compute the matrix multiplication, rather than element wise multiplication . Traverse till the end of the list, multiply every number with the product. dot (np. All the linear algebra revolves around matrices. We traverse array from left to right and multiply elements with results. With scalar multiplication, the order doesn’t matter. pyplot as plt impor The @ operator is now so widely supported in Python libraries that we can say the answer to “How do I do matrix multiplication in Python” has a definitive answer: “Use the @ operator. Matrix multiplication is an essential operation in linear algebra, and Python provides a convenient way to perform this operation. Inner Product of Vectors and Matrices To find the inner product of the vectors and matrices, we can use the inner() method of NumPy. Mar 9, 2024 · The data inside the two-dimensional array in matrix format looks as follows: Step 1) It shows a 2×2 matrix. import torch # Same matrices as In Python, we can implement a matrix as a nested list (list inside a list). mul () function can be used to multiply two matrices. An array class in Numpy is called as ndarray. 3. These matrix multiplication methods include element-wise multiplication, the dot product, and the cross product. There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30. Add two matrices; Transpose a Matrix; Multiply two matrices; Using nested lists as a matrix works for simple computational tasks, however, there is a better way of working with matrices in Python using NumPy package. Examples: Iterative Method: We initialize result as 1. # importing libraries . Inside the function, a for loop is used to iterate over the range from 1 to 11 (excluding 11). split())) here, we have taken two inputs together as row and column for the first matrix similarly, the same thing is done for second matrix p, q are rows and columns respectively. A matrix can be implemented as a nested list in Python (list Python Program #35 - Multiply Two Matrix in PythonIn this video by Programming for beginners we will see Python Program to Multiply Two Matrix in Python for Dec 4, 2023 · Python3. first_array = np. In these problem we use nested List comprehensive. Given two matrix the task is that we will have to create a program to multiply two matrices in python. I need to multiply array vs array. dot I have also tried with rotation_matrix = pre_rotation. A tuple of integers giving the size of the array along each dimension is known as shape of the array. pyplot as plt impor Apr 8, 2020 · Multiplication is the dot product of rows and columns. Let the input 4 matrices be A, B, C and D. 5 days ago · So that was a simple Python program to multiply two matrices. But, Is there any way to improve the performance of matrix multiplication using the normal method. Using nested Loops in Python; Using List Comprehension in Python; Using nested loops in C++; Method #1: Using Nested Loops in Python. Implementation: Python Matrix Multiplication (Python Program to Multiply Two Matrices) Learn how to perform matrix multiplication in Python. Currently what I am doing is rotation_matrix = (a * b * c) but I don't know if this is the correct way to multiply matrices - should I be using . Jun 27, 2018 · I wrote a program in python3 to find out a product of 2 n*n matrices, (where n is a power of 2). shape, they must be broadcastable to a common shape (which becomes the shape of the output). , col1, have values 2,4, and col2 has values 3,5. Let's see an example. we are taking two inputs together that is m, n = list(map(int, input(). Note: In matrix Chain Multiplication we are not bothered about the actual multiplication of the matrices, we simply want to minimize the cost of multiplication. dot(post_rotation Jun 15, 2019 · If you look closely at the output and image of matrix multiplication, you will realize: Every 2 numbers need to be multiplied. Remember that in order to successfully carry out the matrix multiplication, ensure that the number of rows of one matrix should be equal to the number of columns of the other. Last Updated : 24 Feb, 2022. A scalar is just a number, like 1, 2, or 3. array([9, 10, 20]) second_array = np. The multiply_matrices function takes two matrices as input, checks if they can be multiplied, and returns the resulting matrix if the multiplication is valid. xq mn sg yy xk sm zy ss hz ui