Question
Assignment #1 This assignment is to read an input file from the command line, extract data from the input file, perform matrix multiplication operations, save
Assignment #1
This assignment is to read an input file from the command line, extract data from the input file, perform matrix multiplication operations, save the production result to an output file (file name must be output.txt). The input file is a plain text file and has the following format (an example): 2x3 1 8 2 9 3 0
3x4 3 5 23 9 2 4 9 0 38 0 0 1
We will run your script like this: python yourscript InputFileName
Let call the first 2x3 matrix as M1 and the second 3x4 matrix as M2. You script should perform two matrix multiplications: $M1 \times M2$ and $M2^T \times M1^T$. And save the multiplication result into output.txt like this: 95 37 95 11 33 57 234 81
95 33 37 57 95 234 11 81
Below is the sample code were give to follow in class, if this is any help.
import numpy as np import sys
print(len(sys.argv))
if len(sys.argv)<2: print('not enough inputs') sys.exit(1) else: infilename=sys.argv[1]
m1_arr=[] m2_arr=[] m_id=0
with open(infilename) as afile: for aline in afile: if not aline.strip(): continue if 'x' in aline: if m_id==0: m1_dims=[int(ax.strip()) for ax in aline.split('x')] else: m2_dims=[int(ax.strip()) for ax in aline.split('x')] m_id+=1 continue if m_id==1: m1_arr.append([int(ax.strip()) for ax in aline.split()]) else: m2_arr.append([int(ax.strip()) for ax in aline.split()]) m1=np.array(m1_arr) m2=np.array(m2_arr) m3=np.dot(m1,m2) m4=np.dot(m2.T,m1.T)
with open ('output.txt', 'w') as outputf: outputf.write('the first line ') for arow in m3: outputf.write(' '.join(str(x) for x in arow.tolist())) outputf.write(' ') outputf.write(' Second matrix ') for arow in m4: outputf.write(' '.join(str(x) for x in arow.tolist())) outputf.write(' ')
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started