Code Wolfram Mathematica

92 Views Asked by At

The question is very simple, I hope someone knows the code that makes my case.

In fact, writing: q1 /. {"q" <> ToString[1] -> 2} I get q1 instead of 2.

Where am I wrong?

Thanks a lot!!

1

There are 1 best solutions below

2
On BEST ANSWER

Try something more like this:

q1 /. {ToExpression["q" <> "1"] -> 2}

The thing your bit of code is doing is trying to find the string q1 instead of the variable with the name q1.


Clarification:

When you just type the letters q1 in Mathematica, it treats the thing like an expression or a single variable. That is, you can assign it a value such as in

q1=2

And this would make it treat all occurrences of q1 as the number 2. On the other hand, if you type "q1", it thinks you are talking about a string whose content is the character pair q1. So your original code is something akin to:

[expression] /. {[string] -> [value]}

when what you want is

[expression] /. {[expression] -> [value]}

Thanks for posting this question. It gave me a reason to learn a little more about playing with Mathematica, and this may come in handy in future programming projects.