# Plotting doesn't work for expression using ToExpression and StringReplace

I have a very complicated code. I've narrowed down the problem to following structure in the code:

f1[x_, y_] := y^2 + x;
s = "f1"
f2[x_, y_] := ToExpression[StringReplace[s, {"f1" -> "f1[x,y]"}]]
Plot[f2[1, y], {y, 1, 2}]
x = 1;
Plot[f2[x, y], {y, 1, 2}]


The first plot in which I passed 1 as an argument in the function doesn't give a plot. But when I change it to x, with x equal to some value, it works. Please help me in using the first expression (f2[1,y]), I want to use Manipulate to generate plots, which has similar problem as in the first plot.

• f2[x_, y_] = instead of f2[x_, y_] :=, but why are you doing things like this?
– ciao
Jan 18 '17 at 9:11
• There are certainly tricks to get your code working. On the other hand it is almost always a bad idea to go through strings and ToExpression and hardly ever necessary. What you do look like there would be much better ways to solve your actual problem. Can you try to explain why you are using such an approach at all? Jan 19 '17 at 6:59
• @AlbertRetey I'm using Solve to get solutions from few linear equations. These solutions and some other variables in the problem ("f1" in the above code) are later used in the code where I plot some things which require them to be functions of some other quantities which I Manipulate. That's why this approach is required. Do you know any alternative of doing this? Jan 19 '17 at 7:16
• actually I have done similar things without ever needing ToExpression. If you post a simplified example which shows what you do I'm sure you will get good answers which show how to solve your problem without the need of converting to strings and back... Jan 19 '17 at 17:31

You need to evaluate the ToExpression
f1[x_, y_] := y^2 + x;