Implement the scalar-wise, row-variant of the matrix-vector multiplication using nested for loops

Viewed 140

I want to write a function matvec_row_variant_scalar(A,x) that implements the scalar-wise, row-variant of the matrix-vector multiplication, where A is a 2D array, and x is a 1D array. It MUST use two nested loops and scalar-wise access to the entries of and . this is what i have tried.

Matrix12 = np.array([[3, 7, 0], [-9,1,4], [4,6,8]])
vector42 = np.array([5,1,9])

def matvec_row_variant_scalar(A,x):
    row_sum = []
    calc = 0
    for row in A:
        for i in row:
            calc += i * x
    return row_sum.append(calc)

matvec_row_variant_scalar(Matrix12, vector42)
1 Answers

Just use the indices. It'll be easier that way.

def matvec_row_variant_scalar(A,x):
    row_sum = np.zeros(A.shape[0])
    for i in range(A.shape[0]):
        for j in range(A.shape[1]):
            row_sum[i] += A[i, j] * x[j]
    return row_sum

Good luck on your final.

Related