1
$\begingroup$

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.

$\endgroup$
4
  • $\begingroup$ f2[x_, y_] = instead of f2[x_, y_] :=, but why are you doing things like this? $\endgroup$
    – ciao
    Jan 18 '17 at 9:11
  • 1
    $\begingroup$ 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? $\endgroup$ Jan 19 '17 at 6:59
  • $\begingroup$ @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? $\endgroup$
    – siddhesh
    Jan 19 '17 at 7:16
  • $\begingroup$ 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... $\endgroup$ Jan 19 '17 at 17:31
2
$\begingroup$

You need to evaluate the ToExpression

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

Plot[f2[1, y], {y, 1, 2}]

Mathematica graphics

$\endgroup$
1
  • $\begingroup$ Thanks @Nasser, This works. But my complicated expression is not plotting. I think the problem in my expression is somewhere else. I'll look more into it. $\endgroup$
    – siddhesh
    Jan 18 '17 at 9:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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