'Matrix multiplied by a vector without using numpy
Without using numpy in python
I am running into the error "object of type 'int' has no len()" when running the code below when multiplying the matrix C with the vector A.
Any help would be appreciated
A = [3, 4, 8]
C = [[2, 9, 7], [3, 4, 1], [1, 6, 5]]
def MM(C, A):
c = []
for i in range(0, len(C)):
temp=[]
for j in range(0, len(A[0])):
s = 0
for k in range(0, len(C[0])):
s += C[i][k] * A[k][j]
temp.append(s)
c.append(temp)
return c
print("Matrix C multiplied by vector A is: \n", MM(C, A))
Solution 1:[1]
The problem is here:
for j in range(0, len(A[0])):
A[0] is 3, which is an integer and has no attribute len. A is also a 1D array so A[k][j] will also raise an error.
Solution 2:[2]
I haven't stepped through your entire logic to fix the code, but I see the error.
In this line you try to take the length of A[0] for j in range(0, len(A[0]))
You have defined A as:
A = [3,4,8]
Therefore A[0] = 3 and is an integer, which doesn't have a len()
Solution 3:[3]
I think you need A = [[3], [4], [8]]. When the matrix is on the left side of the multiplication, you are multiplying it with a column vector instead of a row vector.
Keeping your code the same, but changing A as mentioned, I get the output:
[[98], [33], [67]]
which corresponds to the 3x1 column vector you would expect to get by doing this matrix multiplication.
If you instead wanted A to be a row vector on the left side of the multiplication, you could set:
A = [[3, 4, 8]]
C = [[2, 9, 7], [3, 4, 1], [1, 6, 5]]
and print
print("The vector A multiplied by the matrix C is: \n", MM(A, C))
to give the output:
[[26, 91, 65]]
This would be a 1x3 row vector multiplied by a 3x3 matrix to give a 1x3 result.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kraigolas |
| Solution 2 | Braden Anderson |
| Solution 3 |
