Mathematica: Extract numerical value when using Solve - wolfram-mathematica

In Mathematica, calling Solve, returns a list of rules, e.g.,
In[1]:= g = Solve[(x - 1) (x - 2) == 0, x]
Out[1]= {{x -> 1}, {x -> 2}}
How can I extract the numerical values 1 or 2 from g?
I tried using Part e.g., g[[1]] but it returns {x -> 1} and not 1.
Please advise.

To complement Belisarius' answer,
x /. g
with g = {{x -> 1}, {x -> 2}}, returns the list
{1, 2}
So to extract the first value, 1, we could use
First[x /. g]
Other alternatives are
x /. g[[1]]
(x /. g)[[1]] (* this is equivalent to the version using First *)
g[[1,1,2]]

x /. g[[1]]
Filler -> Thirty chars minimum

Related

Mathematica FindRoot solve equation

I have a task to solve equation system with FindRoot:
a*x+b*y^2-c*x^2=a-b, a*x^2+b*y^2+b*x-cy=b+c , where a = 10, b = 10, c = 6;
I'm very(!) new to Mathematica and have one day to get to know it.
Any comments on how to solve that equation will be much appreciated!
Thanks!
This starts searching for root at x = 0 and y = 0
eq = {a*x + b*y^2 - c*x^2 == a - b, a*x^2 + b*y^2 + b*x - c*y == b + c}
param = {a -> 10, b -> 10, c -> 6}
result = FindRoot[eq /. param, {x, 0}, {y, 0}]
This only gives you 1 of the two Real solutions. Solve will give you both (and even some solutions with Complex numbers). To test it:
eq /. param /. result
This returns (True, True) so you know you've found the correct root.
To find the solution graphically, use ContourPlot:
ContourPlot[Evaluate[eq /. param], {x, -5, 5}, {y, -5, 5}]
Here is the version with Solve/NSolve
NSolve[{a*x + b*y^2 - c*x^2 == a - b,
a*x^2 + b*y^2 + b*x - c*y == b + c} /. {a -> 10, b -> 10, c -> 6},
{x, y}]
It will give the 4 solutions. If you use Solve instead of NSolve you will have a (large) closed form of each component of each solution.
If you need more digits for the solution, add at the end of the NSolve command the option WorkingPrecision->30 (or any other number of digits. These are quadratics, they can computed to any precision necessary).

Constructing a triadiagonal matrix in Mathematica where nonzero elements contain functions and variables

Suppose I want to construct a matrix A such that A[[i,i]]=f[x_,y_]+d[i], A[[i,i+1]]=u[i], A[[i+1,i]]=l[i], i=1,N . Say, f[x_,y_]=x^2+y^2.
How can I code this in Mathematica?
Additionally, if I want to integrate the first diagonal element of A, i.e. A[[1,1]] over x and y, both running from 0 to 1, how can I do that?
In[1]:= n = 4;
f[x_, y_] := x^2 + y^2;
A = Normal[SparseArray[{
{i_,i_}/;i>1 -> f[x,y]+ d[i],
{i_,j_}/;j-i==1 -> u[i],
{i_,j_}/;i-j==1 -> l[i-1],
{1, 1} -> Integrate[f[x,y]+d[1], {x,0,1}, {y,0,1}]},
{n, n}]]
Out[3]= {{2/3+d[1], l[1], 0, 0},
{u[1], x^2+y^2+ d[2], l[2], 0},
{0, u[2], x^2+y^2+d[3], l[3]},
{0, 0, u[3], x^2+y^2+d[4]}}
Band is tailored specifically for this:
myTridiagonalMatrix#n_Integer?Positive :=
SparseArray[
{ Band#{1, 1} -> f[x, y] + Array[d, n]
, Band#{1, 2} -> Array[u, n - 1]
, Band#{2, 1} -> Array[l, n - 1]}
, {n, n}]
Check it out (no need to define f, d, u, l):
myTridiagonalMatrix#5 // MatrixForm
Note that MatrixForm should not be part of a definition. For example, it's a bad idea to set A = (something) // MatrixForm. You will get a MatrixForm object instead of a table (= array of arrays) or a sparse array, and its only purpose is to be pretty-printed in FrontEnd. Trying to use MatrixForm in calculations will yield errors and will lead to unnecessary confusion.
Integrating the element at {1, 1}:
myTridiagonalMatrixWithFirstDiagonalElementIntegrated#n_Integer?Positive :=
MapAt[
Integrate[#, {x, 0, 1}, {y, 0, 1}]&
, myTridiagonalMatrix#n
, {1, 1}]
You may check it out without defining f or d, as well:
myTridiagonalMatrixWithFirstDiagonalElementIntegrated#5
The latter operation, however, looks suspicious. For example, it does not leave your matrix (or its corresponding linear system) invariant w.r.t. reasonable transformations. (This operation does not even preserve linearity of matrices.) You probably don't want to do it.
Comment on comment above: there's no need to define A[x_, y_] := … to Integrate[A[[1,1]], {x,0,1}, {y,0,1}]. Note that A[[1,1]] is totally different from A[1, 1]: the former is Part[A, 1, 1] which is a certain element of table A. A[1, 1] is a different expression: if A is some table then A[1, 1] is (that table)[1, 1], which is a valid expression but is normally considered meaningless.

Simple power counting

How can one add the number of powers of x in expressions like the following?
x^2f[x]g[x^3]
or
x^2g[x^4]
or
x^2g[x^2f[x^2]]
The counting is such that all these examples must return 6.
I was thinking of using Count with some pattern, but I didn't manage to construct a pattern for this.
Here's my quick hack - some of the behaviour (see the final example) might not be quite what you want:
SetAttributes[countPowers, Listable]
countPowers[expr_, symb_] := Module[{a},
Cases[{expr} /. symb -> symb^a // PowerExpand, symb^n_ :> n,
Infinity] /. a -> 1 // Total]
Then
In[3]:= countPowers[{x^2 f[x] g[x^3], x^2 g[x^4], x^2 g[x^2 f[x^2]]}, x]
Out[3]= {6, 6, 6}
and
In[4]:= countPowers[{x^(2 I) g[x^3], g[x, x^4],
x^2 g[E^(2 Pi I x) , f[x]^x]}, x]
Out[4]= {3 + 2 I, 5, 5}
Since you want to count x as an implicit power of 1, you could use this:
powerCount[x_Symbol][expr_] :=
Tr # Reap[PowerExpand[expr] /. {x^n_ :> Sow[n], x :> Sow[1]}][[2,1]]
powerCount[x] /#
{
x^2f[x]g[x^3],
x^2g[x^4],
x^2g[x^2f[x^2]]
}
{6, 6, 6}
Alternatively, this could be written without Sow and Reap if that makes it easier to read:
powerCount[x_Symbol][expr_] :=
Module[{t = 0}, PowerExpand[expr] /. {x^n_ :> (t += n), x :> t++}; t]
Either form can be made more terse using vanishing patterns, at the possible expense of clarity:
powerCount[x_Symbol][expr_] :=
Tr # Reap[PowerExpand[expr] /. x^n_ | x :> Sow[1 n]][[2, 1]]

What is the correct syntax for this ReplaceAll on a list of lists?

A light-weight question for the experts. I can't seem to figure the correct syntax to this replacement. I have this list
Clear[a, b, c, d]
polesList = {{3, {a, b}}, {5, {c, d}}};
It is of the form of a list with sublists each have the form {order,{x,y}} and I want to generate a new list of this form (x+y)^order
Currently this is what I do, which works:
((#[[2, 1]] + #[[2, 2]])^#[[1]]) & /# polesList
(* -----> {(a + b)^3, (c + d)^5} *)
But I have been trying to learn to use ReplaceAll as it is more clear to me than pure functions, since I can see the pattern better, like this:
Clear[a, b, c, d, n]
polesList = {{3, {a, b}}, {5, {c, d}}};
ReplaceAll[polesList, {n_, {x_, y_}} :> (x + y)^n] (*I thought this will work*)
I get strange result, which is
{(5 + c)^3, {(5 + d)^a, (5 + d)^b}}
What is the correct syntax to do this replacement using ReplaceAll instead of the pure function method?
Thanks
Update:
I find that using Replace, instead of ReplaceAll works, but need to say {1} at the end:
Clear[a, b, c, d, n]
polesList = {{3, {a, b}}, {5, {c, d}}};
Replace[polesList, {n_, {x_, y_}} :> (x + y)^n, {1}]
which gives
{(a + b)^3, (c + d)^5}
But ReplaceAll does not take {1} at the end. I am more confused now which to use :)
The problem is that ReplaceAll inspects all levels of the expression when looking for replacements. The entire expression matches the pattern {n_, {x_, y_}} where:
n matches {3, {a, b}}
x matches 5
y matches {c, d}
So you end up with (5 + {c , d}) ^ {3, {a, b}} which evaluates to the result you see.
There are a few ways to fix this. First, you can change the pattern so that it does not match the outermost list. For example, if the n values are always integers you could use:
ReplaceAll[polesList, {n_Integer, {x_, y_}} :> (x + y)^n]
Or, you could use Replace instead of ReplaceAll, and restrict the pattern matching the first level only:
Replace[polesList, {n_, {x_, y_}} :> (x + y)^n, {1}]
I find that applying replacement rules to the first level of a list is very common. It so happens that Cases, by default, only operates on that level. So I find myself frequently using Cases for level one replacements when I know that all elements will match the pattern:
Cases[polesList, {n_, {x_, y_}} :> (x + y)^n]
This last expression is how I would probably write the desired replacement. Keep in mind, though, that if all elements do not match the pattern, then the Cases approach will drop the mismatches from the result.
The problem is that ReplaceAll looks at all levels in the expression and the first match to the pattern
{n_, {x_, y_}}
in the expression {{3, {a, b}}, {5, {c, d}}} is
{ n=={3, {a, b}}, {x==5, y=={c, d}}}
(if that notation is clear)
So you got the "strange" result
(5 + {c,d})^{3, {a, b}} == {5+c, 5+d}^{3, {a, b}}
== {(5+c)^3, (5+d)^{a, b}} == {(5+c)^3, {(5+d)^a,(5+d)^b}}
The easiest fix, if n is always numeric, is
In[2]:= {{3, {a, b}}, {5, {c, d}}} /. {n_?NumericQ, {x_, y_}} :> (x + y)^n
Out[2]= {(a + b)^3, (c + d)^5}
Where I used the shorthand /. for ReplaceAll.
It might be that using Replace at level 1 is the best option
In[3]:= Replace[{{3, {a, b}}, {5, {c, d}}}, {n_,{x_,y_}}:>(x+y)^n, {1}]
Out[3]= {(a+b)^3,(c+d)^5}
which should be compared with the default replace that works at the top level {0}
In[4]:= Replace[{{3, {a, b}}, {5, {c, d}}}, {n_,{x_,y_}}:>(x+y)^n]
Out[4]= {(5+c)^3,{(5+d)^a,(5+d)^b}}
You could also use ReplaceAll[ ] with Map:
Map[ReplaceAll[#, {n_, {x_, y_}} :> (x + y)^n] &, polesList]
or (using shorthands increasingly)
ReplaceAll[#, {n_, {x_, y_}} :> (x + y)^n] & /# polesList
or
# /. {n_, {x_, y_}} :> (x + y)^n & /# polesList

Diciness with extracting things from a Hold'd expression

Suppose I have a list of param->value rules where the params are symbols that might have values assigned to them. For example:
{a, b, c} = {1, 2, 3};
x = Hold[{a->1, b->2, c->3}];
I need the list wrapped in Hold otherwise it would evaluate to {1->1, 2->2, 3->3}. (I'm open to any alternatives to Hold there if it makes the rest of this easier.)
Now suppose I want to convert x into this:
{"a"->1, "b"->2, "c"->3}
The following function will do that:
f[h_] := Block[{a,b,c}, ToString[#[[1]]]->#[[2]]& /# ReleaseHold#h]
My question: Can you write a version of f where the list of symbols {a,b,c} doesn't have to be provided explicitly?
Here is a way using Unevaluated:
In[1]:= {a, b, c} = {1, 2, 3};
In[2]:= x = Hold[{a -> 1, b -> 2, c -> 3}];
In[3]:= ReleaseHold[
x /. (symb_ -> e_) :> ToString[Unevaluated[symb]] -> e]
Out[3]= {"a" -> 1, "b" -> 2, "c" -> 3}
{a, b, c} = {1, 2, 3};
x = Hold[{a -> 1, b -> 2, c -> 3}];
f[x_] := Cases[x, HoldPattern[z_ -> y_] :>
StringTake[ToString[(Hold#z)], {6, -2}] -> y, 2];
f[x] // InputForm
Out:
{"a" -> 1, "b" -> 2, "c" -> 3}
Perhaps not very elegant, but seems to work.
This is a bit of an old question, but I think there's an answer that combines the virtues of both Andrew Moylan's answer and belisarius' answer. You really want to have lists of rules with HoldPattern on the left-hand side, instead of lists of rules that have Hold wrapped around the whole thing, so that you can actually use the rules without having to go through any sort of ReleaseHold process.
In[1]:= {a, b, c} = {1, 2, 3};
Unevaluated can also be helpful in constructing the sort of list you want:
In[2]:= x = Thread[HoldPattern /# Unevaluated[{a, b, c}] -> Range[3]]
Out[2]= {HoldPattern[a] -> 1, HoldPattern[b] -> 2, HoldPattern[c] -> 3}
Now you can do what you want with rule replacement. It's a bit involved, but it's something I find myself doing over and over and over again. You may notice that this list of rules has almost exactly the form of a list of OwnValues or DownValues, so being able to manipulate it is very helpful. The trick is using HoldPattern and Verbatim in concert:
In[3]:= f[rules_] :=
Replace[rules,
HoldPattern[Verbatim[HoldPattern][s_Symbol] -> rhs_] :>
With[{string = ToString[Unevaluated[s]]},
string -> rhs], {1}]
The level spec on Replace is just there to make sure nothing unexpected happens if rhs is itself a rule or list of rules.
In[4]:= f[x] // InputForm
Out[4]= {"a" -> 1, "b" -> 2, "c" -> 3}

Resources