Question

I need help writing a program in python that reads from a file and performs matrix...

I need help writing a program in python that reads from a file and performs matrix multiplication. the file has this format

1 
4 
2 
1 1 1 1
1 1
2 2
3 3
4 4

which means :

1  #rows in A
4  #cols in A, rows in B
2  #cols in B
Matrix A contents:
 1 1 1 1

Matrix B contents:
 1 1
 2 2
 3 3
 4 4

i need to be able to read in the file, and then multiply the two matrices and print out the result .. thanks

0 0
Add a comment Improve this question Transcribed image text
Answer #1
SOURCE CODE:

*Please follow the comments to better understand the code.

**Please look at the Screenshot below and use this code to copy-paste.

***The code in the below screenshot is neatly indented for better understanding.


# function to print the matrix
def print_matrix(matrix, rows, cols):
    for i in range(rows):
        for j in range(cols):
            print(matrix[i][j], end=' ')
        print()


# open file
file_name = input("Enter the file name: ")
with open(file_name) as file:
    # read data from file
    data = file.readlines()

    # read the columns and rows
    rows_a = int(data[0])
    col_a_row_b = int(data[1])
    cols_b = int(data[2])

    # Read contents of matrix a
    matrix_a = []
    for i in range(rows_a):
        # read each row and append it to matrix
        row = [int(x) for x in data[3 + i].split()]
        matrix_a.append(row)
    # Read contents of matrix b
    matrix_b = []
    for i in range(col_a_row_b):
        # read each row and append it to matrix
        row = [int(x) for x in data[3 + i + rows_a].split()]
        matrix_b.append(row)

    # print the matrices
    print('Matrix A contents:')
    print_matrix(matrix_a, rows_a, col_a_row_b)
    print('Matrix B contents:')
    print_matrix(matrix_b, col_a_row_b, cols_b)

    # take an empty list
    res = []
    # perform the multiplication
    for i in range(rows_a):
        row = []
        for j in range(cols_b):
            s = 0
            for k in range(col_a_row_b):
                # resulted sum
                s += matrix_a[i][k] * matrix_b[k][j]
            row.append(s)
        # append the row to result
        res.append(row)

    print("\nThe result is:")
    print_matrix(res, rows_a, cols_b)

========

OUTPUT

Add a comment
Know the answer?
Add Answer to:
I need help writing a program in python that reads from a file and performs matrix...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a program that performs the following: - Reads from the file "myfile.txt" using readlines() -...

    Write a program that performs the following: - Reads from the file "myfile.txt" using readlines() - Prints out the contents of the file "myfile.txt", that was read into a list by readlines(). Note that this should not look like a list, so you will need to loop through the list created by readlines and print the text. - Use the try/except method to create the file if it does not exist - If the file does not exist, prompt the...

  • I need a lot of questions for practicing writing and reading file in Python program to...

    I need a lot of questions for practicing writing and reading file in Python program to study for my final, but I couldn't find it anywhere. Help me, please! :( And also, I barely understand file in Python, so the questions need to be from easy and moderate, please! Thanks for helping!

  • Python Programming 4th Edition: Need help writing this program below. I get an error message that...

    Python Programming 4th Edition: Need help writing this program below. I get an error message that says that name is not defined when running the program below. My solution: def main(): filename = "text.txt" contents=f.read() upper_count=0 lower_count=0 digit_count=0 space_count=0 for i in contents: if i.isupper(): upper_count+=1 elif i.islower(): lower_count+=1 elif i.isdigit(): digit_count+=1 elif i.isspace(): space_count+=1 print("Upper case count in the file is",upper_count) print("Lower case count in the file is",lower_count) print("Digit count in the file is",digit_count) print("Space_count in the file is",space_count)...

  • Please help me out with this assignment. Please read the requirements carefully. And in the main...

    Please help me out with this assignment. Please read the requirements carefully. And in the main function please cout the matrix done by different operations! Thanks a lot! For this homework exercise you will be exploring the implementation of matrix multiplication using C++ There are third party libraries that provide matrix multiplication, but for this homework you will be implementing your own class object and overloading some C+ operators to achieve matrix multiplication. 1. 10pts] Create a custom class called...

  • JAVA PROGRAM. I need to write a program in java that will perform matrix addition and both matric...

    JAVA PROGRAM. I need to write a program in java that will perform matrix addition and both matrices have N rows and M columns, N>1 and M>1. The two matrices must be divided to four equal size sub-matrices and each sub-matrix has dimensions N/2 X M/2. I need to create four threads and each thread performs a sub-set of addition on one pair of the sub-matrices. I also need an extra thread for networking. The network part of this uses...

  • PYTHON PROGRAMMING LANGUAGE Task 5 Open a csv file for writing create 3 rows that store...

    PYTHON PROGRAMMING LANGUAGE Task 5 Open a csv file for writing create 3 rows that store username, first name, last name and age data (four columns) write the data to the csv file under the correct column Task 6 Open the file in task 5) and read its contents Output the content in a tabular format of columns and values

  • Problem 1 Write your code in the file MatrixOps.java. . Consider the following definitions from matrix...

    Problem 1 Write your code in the file MatrixOps.java. . Consider the following definitions from matrix algebra: A vector is a one-dimensional set of numbers, such as [42 9 20]. The dot product of two equal-length vectors A and B is computed by multiplying the first entry of A by the first entry of B, the second entry of A by the second entry of B, etc., and then summing these products. For example, the dot product of [42 9...

  • Consider python please for this problem: I did a python program to read the first 20 lines from a...

    Consider python please for this problem: I did a python program to read the first 20 lines from a file and here is the code holder = 20 lines = 3 file = "123456.pssm" _file = ".txt" while 1:         out_file = input("[OUTPUT] - Please enter the name of file: ") + _file         if (not _file):         print("Filename not specified - Please Try Again\n")         continue     break with open(_file, "a") as e:     with open(file, "r") as f:         for num, line in enumerate(f, 1):                        ...

  • C++ must use header files and implementation files as separate files. I’ll need a header file,...

    C++ must use header files and implementation files as separate files. I’ll need a header file, implementation file and the main program file at a minimum. Compress these files into one compressed file. Make sure you have adequate documentation. We like to manipulate some matrix operations. Design and implement a class named matrixMagic that can store a matrix of any size. 1. Overload the addition, subtraction, and multiplication operations. 2. Overload the extraction (>>) and insertion (<<) operators to read...

  • I need this python program to access an excel file, books inventory file. The file called...

    I need this python program to access an excel file, books inventory file. The file called (bkstr_inv.xlsx), and I need to add another option [search books], option to allow a customer to search the books inventory, please. CODE ''' Shows the menu with options and gets the user selection. ''' def GetOptionFromUser(): print("******************BookStore**************************") print("1. Add Books") print("2. View Books") print("3. Add To Cart") print("4. View Receipt") print("5. Buy Books") print("6. Clear Cart") print("7. Exit") print("*****************************************************") option = int(input("Select your option:...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT