There are several examples and questions regarding Map
, but I couldn't find what I need.
This is a minimal working example.
I have two functions
$\qquad f=x^4+y^4-1$,
and
$\qquad g=x^2-4$.
One way to find the solution set would be to find the values of $x$ from $g=0$ and then substitute those values into $f$. Then solve for $f=0$ to obtain the values of $y$. I need to club the corresponding values of $x$ and $y$ together to form the solution set.
I have correctly implemented a solution using a For
loop. However, I was wondering if I could use a nested Map
or something simpler. I come from a C++
background and a For
loop is the intuitive and normal solution for most work involving array manipulation. However, I think For
loops hurt writing efficient code in Mathematica
(I suppose).
Existing solution:
f = x^4 + y^4 - 1;
g = x^2 - 4;
solx = Solve[g == 0, x];
For[i = 1, i <= Length[solx], i++,
solytemp = NSolve[(f /. solx[[i]]) == 0, y];
temp = Flatten[{solx[[i]], #}] & /@ solytemp;
If[i == 1, solxy = temp, AppendTo[solxy, #] & /@ temp;];
];
solxy
{{x -> -2, y -> -1.39158 - 1.39158 I}, {x -> -2, y -> -1.39158 + 1.39158 I}, {x -> -2, y -> 1.39158 - 1.39158 I}, {x -> -2, y -> 1.39158 + 1.39158 I}, {x -> 2, y -> -1.39158 - 1.39158 I}, {x -> 2, y -> -1.39158 + 1.39158 I}, {x -> 2, y -> 1.39158 - 1.39158 I}, {x -> 2, y -> 1.39158 + 1.39158 I}}
Please note that this is an MWE and the actual polynomials may be of much higher order.
Update 1
The solutions are to be found in steps and then clubbed together, as the polynomials are big. I also use my own modules instead of NSolve
depending on how the solution is to be obtained and the problem.
I am aware of using Solve
for multiple polynomials, however I am refraining from using that as the system is huge.
Solve[{f == 0, g == 0}, {x, y}]
I was hoping if something like below could be used (the code below does not work)
{#1, #2} & /@ NSolve[(f /. #1) == 0, y] & /@ solx
Update 2
Using the answer given by @Jason, I could do the following to get the result:
f = x^4 + y^4 - 1
g = x^2 - 4
solx = Solve[g == 0, x];
solxy = Flatten[
solf2[xtrial_] :=
Union[#, xtrial] & /@ NSolve[(f /. xtrial) == 0, y]; (solf2[#] & /@
solx), 1];
Is there a way to bypass assigning a function. I don't want to end up creating several functions. It is a good solution nevertheless.