0
$\begingroup$

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"}][[2]]

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"}][[2]]

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.

$\endgroup$
5
  • $\begingroup$ Try ToExpression - also, side note, consider not using single-character uppercase symbol names like M. You might be redefining system symbols! $\endgroup$
    – Carl Lange
    Jan 10, 2019 at 10:49
  • $\begingroup$ Hmm.. Maybe I'm not using it correctly... I'll post the output of it in the question. $\endgroup$ Jan 10, 2019 at 10:58
  • $\begingroup$ 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? $\endgroup$
    – Carl Lange
    Jan 10, 2019 at 10:59
  • $\begingroup$ Yes, that's what I am expecting. I'll try again. Thanks for the help. $\endgroup$ Jan 10, 2019 at 11:05
  • 1
    $\begingroup$ 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. $\endgroup$ Jan 10, 2019 at 11:06

1 Answer 1

1
$\begingroup$

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.

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.