# Convert string representation of matrix to matrix

I have a Python script which generates and outputs Mathematica matrices. I use RunProcess to run my Python script and I extract the StandardOutput which is the Mathematica matrix as a string.

What I would like to do is take that string and perform matrix operations on it, for example, compute its eigenvectors.

For example:

RunProcess[{"python", "myscript.py"}][]


which outputs

{{0, 0, 1-r, 0, 0, 1-r},{1-r, 1-r, 0, 1-r, 0, 0},{0, 0, 0, 0, 1,
0},{0, 0, 0, 0, 0, 0},{0, 0, r, 0, 0, r},{r, r, 0, r, 0, 0}}


and I would like to have something like

MyMatrix[r_] := RunProcess[{"python", "myscript.py"}][]


Which would give me the equivalent of:

MyMatrix[r_] := {{0, 0, 1-r, 0, 0, 1-r},{1-r, 1-r, 0, 1-r, 0, 0},{0, 0, 0, 0, 1,
0},{0, 0, 0, 0, 0, 0},{0, 0, r, 0, 0, r},{r, r, 0, r, 0, 0}}


which I can perform matrix operations on. The problem is, when I extract the standard out, the output is in a string format and it isn't converting to a symbolic matrix automatically. Is there some command I can use? Thanks.

• Try ToExpression - also, side note, consider not using single-character uppercase symbol names like M. You might be redefining system symbols! Jan 10, 2019 at 10:49
• Hmm.. Maybe I'm not using it correctly... I'll post the output of it in the question. Jan 10, 2019 at 10:58
• ToExpression["{{1-r, 1-r, 0},{0, 0, 1},{r, r, 0}}"] gives me a 3x3 matrix (you could test with Dimensions). You can call (for example) Eigenvalues on it and get {1, 0, -r}. Is that what you are expecting? Jan 10, 2019 at 10:59
• Yes, that's what I am expecting. I'll try again. Thanks for the help. Jan 10, 2019 at 11:05
• Ah... I did something stupid.. I had already defined r as something. It works. Thanks a lot. If you add your comment as an answer, I will accept it as correct. Jan 10, 2019 at 11:06

You're looking for the function ToExpression.
ToExpression["{{1-r, 1-r, 0},{0, 0, 1},{r, r, 0}}"]

will transform the string "{{1-r, 1-r, 0},{0, 0, 1},{r, r, 0}}" into a 3x3 matrix.