Reputation: 45
a="1 2 3; 4 5 6"
. How do i express this as a matrix [1 2 3; 4 5 6]
in Python? b
, convert to a matrix and find a x b
. Upvotes: 0
Views: 25232
Reputation: 8786
This is one way to do it, split the string at ;
, then go through each string, split at ' '
and then go through that, convert it to an int and append to a sublist, then append that sublist to another list:
a = "1 2 3; 4 5 6"
aSplit = a.split('; ')
l = []
for item in aSplit:
subl = []
for num in item.split(' '):
subl.append(int(num))
l.append(subl)
print l
Upvotes: 2
Reputation: 117856
You can use the numpy
module to create a matrix directly from a string in matlab type format
>>> import numpy as np
>>> a="1 2 3; 4 5 6"
>>> np.matrix(a)
matrix([[1, 2, 3],
[4, 5, 6]])
You can use the same library to do matrix multiplication
>>> A = np.matrix("1 2 3; 4 5 6")
>>> B = np.matrix("2 3; 4 5; 6 7")
>>> A * B
matrix([[28, 34],
[64, 79]])
Go read up on the numpy
library, it is a very powerful module to do all of the type of work that you are referring to.
Upvotes: 4