1
$\begingroup$

I want to solve an equation and substitute it into a Plot expression. My code looks something like this

a[b_, x_] := bx + 1;
sol = Solve[(1 + b)x + 1 == 0, b]

I want to use the solution of b and substitute it to get the value of a and then plot it. I expect the result to be -x and I expected to see a plot of y = -x.

Plot[a[b /. sol, x], {x, 1, 1000}]

However, I don't get anything. Can anyone please help?

$\endgroup$
3
  • 9
    $\begingroup$ You're missing a space between b and x in the definition of a. Works fine if you fix that. $\endgroup$ Commented Mar 21, 2013 at 7:23
  • $\begingroup$ Is the code you gave a minimized example? If so, was the above the problem with your actual code as well? $\endgroup$ Commented Mar 21, 2013 at 10:13
  • $\begingroup$ Yes it is the minimized example. I tried to make it as simple as possible. Yes, it is working in my real code. Thx $\endgroup$ Commented Mar 21, 2013 at 11:07

2 Answers 2

6
$\begingroup$

The problem here is simply that Mathematica sees bx as a (new, undefined) variable and not as the product of b and x. If we switch to a[b_, x_] := b x + 1; the plot appears as intended.

Although it doesn't cause any trouble in this case, it's important to be aware of the output of the functions you're using. For instance, in order to allow for multiple multivariate solutions, Solve[] outputs a list of lists of Rules. This leads to the following behaviour:

a[b /. sol, x]

(* ==> {-x} *)

We can perform algebra with (and plot) lists like this just fine, but in more complicated array-based work you might end up with a hard-to-track-down bug.

$\endgroup$
0
$\begingroup$

The others already have pointed out the problem of your code. But I think it's not bad to say that using 1-D Math input typing usually avoids encountering such mistakes. To type your code in 1-D Math input mode, you should use * whenever you have a multiplication. For substitution in your code, I prefer to use ReplaceAll command. And in case your Solve gives more than one solution, let's say you have a degree two polynomial equation and it gives two different solutions, then you need to tell Mathematica to choose which solution to substitute in your expression. So I prefer to type sol[[1]] which means the first element of the list of solutions. If you avoid mentioning the index of the solution that you want, then Mathematica will give you a list containing result of the substitution for each of the solutions. So anyway, your code written in 1-D Math input format and my taste will be as the following.

a[b_,x_]:=b*x+1;
sol=Solve[(1+b)*x+1==0,b]
Plot[ReplaceAll[sol[[1]]][a[b,x]],{x,1,1000}]

Running it, you will get the following result.

enter image description here

$\endgroup$

Your Answer

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

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