0
  1. 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?
  2. I want to then use another such string b, convert to a matrix and find a x b.
1
  • You should start by trying to code it by yourself and show us some of the ideas you came up with. Commented Aug 7, 2015 at 12:42

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.