|
| 1 | +def vector_inner_product(a,b): |
| 2 | + if len(a)!=len(b): |
| 3 | + return "The two vectors should be of same dimensions" |
| 4 | + product=0 |
| 5 | + for i in range(len(a)): |
| 6 | + product=product+a[i]*b[i] |
| 7 | + return product |
| 8 | + |
| 9 | +def check_orthogonal(a,b): |
| 10 | + if vector_inner_product(a,b)==0: |
| 11 | + return True |
| 12 | + else: |
| 13 | + return False |
| 14 | + |
| 15 | +def linear_combination_len2(r,a,b): |
| 16 | + """ |
| 17 | + returns a linear combinations of vectors of length 2,solving by elimination |
| 18 | + 1st equation coefficients- |
| 19 | + rightside=r[0] |
| 20 | + x_coefficient=a[0] |
| 21 | + y_coefficient=b[0] |
| 22 | + 2nd equation coefficients |
| 23 | + rightside=r[1] |
| 24 | + x_coefficient=a[1] |
| 25 | + y_coefficient=b[1] |
| 26 | + """ |
| 27 | + original=(r[0],a[0],b[0]) |
| 28 | + if a[0]>=a[1]: |
| 29 | + multiplier=a[0]/a[1] |
| 30 | + r[1]=r[1]*multiplier |
| 31 | + a[1]=a[1]*multiplier |
| 32 | + b[1]=b[1]*multiplier |
| 33 | + else: |
| 34 | + multiplier=a[1]/a[0] |
| 35 | + r[0]=multiplier*r[0] |
| 36 | + a[0]=multiplier*a[0] |
| 37 | + b[0]=multiplier*b[0] |
| 38 | + |
| 39 | + assert a[0]-a[1]==0 |
| 40 | + y=(r[0]-r[1])/(b[0]-b[1]) |
| 41 | + x=(original[0]-y*original[2])/original[1] |
| 42 | + return x,y |
| 43 | + |
| 44 | +def transpose(p): |
| 45 | + """returns the transpose t of a matrix p""" |
| 46 | + t=[] |
| 47 | + for i in range(len(p)): |
| 48 | + row=[] |
| 49 | + for j in range(len(p[i])): |
| 50 | + row.append(p[j][i]) |
| 51 | + t.append(row) |
| 52 | + return t |
| 53 | + |
| 54 | +def matrix_multiply(a,b): |
| 55 | + res=[] |
| 56 | + for row in a: |
| 57 | + r=[] |
| 58 | + for column in b: |
| 59 | + r.append(vector_inner_product(row,column)) |
| 60 | + res.append(r) |
| 61 | + return res |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + print("1) ",vector_inner_product([5,2],[6,8])) |
| 69 | + print("2) ",vector_inner_product([3,10],[1,7])) |
| 70 | + print("3) ",vector_inner_product([1,-2,4],[2,3,3])) |
| 71 | + print("4) ",check_orthogonal([1,5],[-5,1])) |
| 72 | + print("5) ",check_orthogonal([3,6,2],[1,4,3])) |
| 73 | + print("6) ", linear_combination_len2([5,5],[1,2],[3,1])) |
| 74 | + print("7) ", linear_combination_len2([-7,16],[1,2],[3,1])) |
| 75 | + print("8 ",matrix_multiply([[2,3],[1,4]],[[3,-2]])) |
| 76 | + print("9 ",matrix_multiply([[1,4],[0,5]],[[1,1]])) |
| 77 | + print("10 ",matrix_multiply([[-2,6],[9,4]],[[3,-5],[3,1]])) |
| 78 | + |
| 79 | + |
| 80 | + |
0 commit comments