- I have a string
a="1 2 3; 4 5 6". How do i express this as a matrix[1 2 3; 4 5 6]in Python? - I want to then use another such string
b, convert to a matrix and finda x b.
-
You should start by trying to code it by yourself and show us some of the ideas you came up with.Peut22– Peut222015-08-07 12:42:02 +00:00Commented Aug 7, 2015 at 12:42
Add a comment
|
2 Answers
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.
Comments
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