I have a task to solve some system of equations with NSolve and print graph of it, depends on parameters.
Something like this (maybe it is not a good example and does not always have a solution, but it just for example).
x+y==a
x-y==b
and I need to plot 3D graph of y(a,b) and x(a,b). Let's assume that for any a and b my system has a solution. My Real system is very complicated and has some complicated functions which are calculated through NIntegrate[].
I managed to find a solution and with Table[] function generate array of all possible values in the form
{
{{a1,b1},{{x->x1,y->y1}}},
{{a2,b2},{{x->x2,y->y2}}}
...
}
or with numbers
{
{{0.1,0.1},{{x->1.5,y->2.5}}},
{{0.1,0.2},{{x->1.6,y->2.6}}}
...
}
Let's call it "myInitialSolution" It took just 10 seconds for me.
Later I tried to convert it to another format, which is good for Interpolation function.
I converted it with Table function like this
xArraySolution := Table[{myInitialSolution[[i]][[1]],
x /. myInitialSolution[[i]][[2]][[1]][[1]]]]}, {i, 1, maxPoints*maxPoints, 1}];
and the same for y. maxPoints - is how many point for x I have in initial solution. It gave me array like this
{
{{a1,b1},x1},
{{a2,b2},x2}
...
}
or with numbers like this
{
{{0.1,0.1},1.5},
{{0.1,0.2},1.6}
...
}
It took already 20 minutes! I do not understand why just to convert array it took so long? What I did wrong?
Later to be able to plot a smooth graph I applied Interpolation function on it like this
xSolution[a, b] := Interpolation[xArraySolution][a, b];
and after this just to calculate one point like this
xSolution[0.15, 0.15]
which returns me for example
1.55
it took 10 minutes just to calculate 1 number!!!
My questions are
why it so slow may be I am doing something wrong? Because I got all numbers in 10 seconds, and later just to rearrange them it took 20 minutes.
Looks like each time when I use my final function xSolution[a,b] Mathematica tries to solve system from the beginning. By I already have all numbers in memory. Why it is doing so?
Can I just copy somehow data from one array to another and make another array independent copy? Just to avoid running NSolve each time, when I need to calculate something. In my example I would like to copy data from myInitialSolution to xArraySolution completely independently. In other words it would be good to have xArraySolution as completely new in memory array. Of course if I make a copy and paste from keyboard it will work, but it is not a good solution :)
SetDelayed
all over the place is causing the slowdown. However, I do not see the code which makes thexArraySolution
be generated so slowly. I can only make a wild guess, that you useSetDelayed
in the definition ofmyInitialSolution
as well, so every time you're runningxArraySolution
, you're solving the equations all over again. $\endgroup$