I don't know what am doing wrong.
amount={20,30,40,50,60,70,80,90,120,130,140,150,160,170,180,190,200}
capa={12,32,50,65,87,110,145,185,320,380,445,510,580,650,710,790,860}
data=Transpose[{amount,capa}]
nlm=NonlinearModelFit[data,A*(1-Exp[-b*x]),{A,B},x]
Using this I get overflow compilation error and nothing happens.
When I use the exact same fit in Origin or Matplotlib I get correct fit with A=-135and B=-0.01017.
As you could read on the Documentation page for the "General::ovfl" message you got, the problem here possible in bad starting values chosen by NonlinearModelFit. Let us try to specify better starting values:
nlm = NonlinearModelFit[data, a*(1 - Exp[-b*x]), {{a, -1}, {b, 0}}, x];
nlm["BestFitParameters"]
(*=> {a -> -134.847, b -> -0.0101706} *)
Right answer and no error messages.
Related
I need to solve a diferential equation of the form w'=g(t,w(t)) where g is defined as follows
g[t_, w_] := {f1[t, {w[[3]], w[[4]]}], f2[t, {w[[3]], w[[4]]}], w[[1]],w[[2]]};
and f1, f2 are
f1[t_, y_] := Sum[\[Mu][[i]] (s[[i]] - y)/Norm[s[[i]] - y]^2, {i, 1, 5}][[1]];
f2[t_, y_] := Sum[\[Mu][[i]] (s[[i]] - y)/Norm[s[[i]] - y]^2, {i, 1, 5}][[2]];
Everything else is defined properly and is not the cause of the error.
Yet when I use
sout = NDSolve[{y'[tvar] == g[tvar, y[tvar]],
y[0] == {Cos[Pi/6], Sin[Pi/6], 0, 0}}, y, {tvar, 0, 2}, Method -> "ExplicitRungeKutta"];
I get the error
Part::partw: Part 3 of y[tvar] does not exist.
Part::partw: Part 4 of y[tvar] does not exist.
I have looked in other questions and none of them solved this problem.
You want to find a function in $R^4$ satisfying a differential equation.
I don't think DSolve and NDSolve have a standard way of manipulating vectorial differential equations except by representing each component with an explicit name or an index for the dimensions.
Here is a working example, that can be executed without Method specification in dimension 4 with notations similar to your problem:
sout={w1[t],w2[t],w3[t],w4[t]} /. NDSolve[{
w1'[t]== t*w2[t],
w2'[t]== 2*t*w1[t],
w3'[t]==-2*w2[t]+w1[t],
w4'[t]== t*w3[t]-w1[t]+w2[t],
w1[0]==0,
w2[0]==1,
w3[0]==1,
w4[0]==0
},{w1[t],w2[t],w3[t],w4[t]},{t,0,2}]
ParametricPlot[{{sout[[1, 1]], sout[[1, 3]]}, {sout[[1, 2]], sout[[1, 4]]}}, {t, 0, 2}]
I think you will be able to adapt this working example to your needs.
I didn't use your original problem as I wanted to focus on the specification for Mathematica, not on the mathematics of your equation. There are constants involved such as Mu and s that you do not give.
I often have a list of pairs, as
data = {{0,0.0},{1,12.4},{2,14.6},{3,25.1}}
and I want to do something, for instance Rescale, to all of the second elements without touching the first elements. The neatest way I know is:
Transpose[MapAt[Rescale, Transpose[data], 2]]
There must be a way to do this without so much Transposeing. My wish is for something like this to work:
MapAt[Rescale, data, {All, 2}]
But my understanding is that MapAt takes Position-style specifications instead of Part-style specifications. What's the proper solution?
To clarify,
I'm seeking a solution where I don't have to repeat myself, so lacking double Transpose or double [[All,2]], because I consider repetition a signal I'm not doing something the easiest way. However, if eliminating the repetition requires the introduction of intermediate variables or a named function or other additional complexity, maybe the transpose/untranspose solution is already correct.
Use Part:
data = {{0, 0.0}, {1, 12.4}, {2, 14.6}, {3, 25.1}}
data[[All, 2]] = Rescale # data[[All, 2]];
data
Create a copy first if you need to. (data2 = data then data2[[All, 2]] etc.)
Amending my answer to keep up with ruebenko's, this can be made into a function also:
partReplace[dat_, func_, spec__] :=
Module[{a = dat},
a[[spec]] = func # a[[spec]];
a
]
partReplace[data, Rescale, All, 2]
This is quite general is design.
I am coming late to the party, and what I will describe will differ very little with what #Mr. Wizard has, so it is best to consider this answer as a complementary to his solution. My partial excuses are that first, the function below packages things a bit differently and closer to the syntax of MapAt itself, second, it is a bit more general and has an option to use with Listable function, and third, I am reproducing my solution from the past Mathgroup thread for exactly this question, which is more than 2 years old, so I am not plagiarizing :)
So, here is the function:
ClearAll[mapAt,MappedListable];
Protect[MappedListable];
Options[mapAt] = {MappedListable -> False};
mapAt[f_, expr_, {pseq : (All | _Integer) ..}, OptionsPattern[]] :=
Module[{copy = expr},
copy[[pseq]] =
If[TrueQ[OptionValue[MappedListable]] && Head[expr] === List,
f[copy[[pseq]]],
f /# copy[[pseq]]
];
copy];
mapAt[f_, expr_, poslist_List] := MapAt[f, expr, poslist];
This is the same idea as what #Mr. Wizard used, with these differences: 1. In case when the spec is not of the prescribed form, regular MapAt will be used automatically 2. Not all functions are Listable. The solution of #Mr.Wizard assumes that either a function is Listable or we want to apply it to the entire list. In the above code, you can specify this by the MappedListable option.
I will also borrow a few examples from my answer in the above-mentioned thread:
In[18]:= mat=ConstantArray[1,{5,3}];
In[19]:= mapAt[#/10&,mat,{All,3}]
Out[19]= {{1,1,1/10},{1,1,1/10},{1,1,1/10},{1,1,1/10},{1,1,1/10}}
In[20]:= mapAt[#/10&,mat,{3,All}]
Out[20]= {{1,1,1},{1,1,1},{1/10,1/10,1/10},{1,1,1},{1,1,1}}
Testing on large lists shows that using Listability improves the performance, although not so dramatically here:
In[28]:= largemat=ConstantArray[1,{150000,15}];
In[29]:= mapAt[#/10&,largemat,{All,3}];//Timing
Out[29]= {0.203,Null}
In[30]:= mapAt[#/10&,largemat,{All,3},MappedListable->True];//Timing
Out[30]= {0.094,Null}
This is likely because for the above function (#/10&), Map (which is used internally in mapAt for the MappedListable->False (default) setting, was able to auto-compile. In the example below, the difference is more substantial:
ClearAll[f];
f[x_] := 2 x - 1;
In[54]:= mapAt[f,largemat,{All,3}];//Timing
Out[54]= {0.219,Null}
In[55]:= mapAt[f,largemat,{All,3},MappedListable->True];//Timing
Out[55]= {0.031,Null}
The point is that, while f was not declared Listable, we know that its body is built out of Listable functions, and thus it can be applied to the entire list - but OTOH it can not be auto-compiled by Map. Note that adding Listable attribute to f would have been completely wrong here and would destroy the purpose, leading to mapAt being slow in both cases.
How about
Transpose[{#[[All, 1]], Rescale[#[[All, 2]]]} &#data]
which returns what you want (ie, it does not alter data)
If no Transpose is allowed,
Thread[Join[{#[[All, 1]], Rescale[#[[All, 2]]]} &#data]]
works.
EDIT: As "shortest" is now the goal, best from me so far is:
data\[LeftDoubleBracket]All, 2\[RightDoubleBracket] = Rescale[data[[All, 2]]]
at 80 characters, which is identical to Mr.Wizard's... So vote for his answer.
Here is another approach:
op[data_List, fun_] :=
Join[data[[All, {1}]], fun[data[[All, {2}]]], 2]
op[data, Rescale]
Edit 1:
An extension from Mr.Wizard, that does not copy it's data.
SetAttributes[partReplace, HoldFirst]
partReplace[dat_, func_, spec__] := dat[[spec]] = func[dat[[spec]]];
used like this
partReplace[data, Rescale, All, 2]
Edit 2:
Or like this
ReplacePart[data, {All, 2} -> Rescale[data[[All, 2]]]]
This worked for me and a friend
In[128]:= m = {{x, sss, x}, {y, sss, y}}
Out[128]= {{2, sss, 2}, {y, sss, y}}
In[129]:= function[ins1_] := ToUpperCase[ins1];
fatmap[ins2_] := MapAt[function, ins2, 2];
In[131]:= Map[fatmap, m]
Out[131]= {{2, ToUpperCase[sss], 2}, {y, ToUpperCase[sss], y}}
I am trying to calculate a definite integral. I write:
NIntegrate[expression, {x, 0, 1}, WorkingPrecision -> 100]
"expression" is described below. The WorkingPrecision was added in to help with another error.
I get an error:
"NIntegrate::ncvb: NIntegrate failed to converge to prescribed
accuracy after 9 recursive bisections in x near {x} = {<<156>>}.
NIntegrate obtained <<157>> and <<160>> for the integral and error
estimates. >>"
Why am I getting this error for near{x} = {<<156>>} when I am only looking at 0<x<1? And what do the double pointy brackets around the number mean?
The expression is really long, so I think it would be more meaningful to show how I generate it.This is a basic version (some of the exponents I need to be variables, but these are the lowest values, and I still get the error).
F[n_] := (1 - (1 - F[n-1])^2)^2;
F[0] = x;
Expr[n_]:= (1/(1-F[n]))Integrate[D[F[n],x]*x,{x,x,1}];
I get the error when I integrate Expr[3] or higher. Oddly, when I use regular Integrate and then //N at the end, I get a complex number for n=2.
The <<156>> does not mean that the integral is being evaluated at x=156. <<>> is called Skeleton and is used to indicate that a large output was suppressed. From the documentation:
Skeleton[n]
represents a sequence of n omitted elements in an expression printed with Short or Shallow. The standard print form for Skeleton is <<n>>.
Coming to your integral, here's the error that I get:
So you can see that this long number was suppressed in your case (depending on your preferences). The last >> is a link that takes you to the corresponding error message in the documentation.
If you try the advice in the document, which is to increase MaxRecursion, you'll eventually get a new error ::slwcon
So this now tells you that either your WorkingPrecision is too small or that you have a singularity (which is brought on by a small working precision). Increasing WorkingPrecision to 200 gives the following output:
You can look a little further into the nature of your expressions.
num = Numerator#Expr#3;
den = Denominator#Expr#3;
Plot[{num, den}, {x, 0, 1}, WorkingPrecision -> 100, PlotRange -> All]
So beyond 0.7ish, your expression has the potential for serious stability issues, resulting in singularities. It is the numerator rather than the denominator, that requires high precision to converge to the right value.
num /. x -> 0.99
num /. x -> 0.99`100
Out[1]= -0.015625
Out[2]= 1.2683685178049112809413795626911317545171610885215799438968\
06379991565*10^-14
den /. x -> 0.99
den /. x -> 0.99`100
Out[3]= 1.28786*10^-14
Out[4]= 1.279743968014714505561671861369465844697720803022743298030747945923286\
915425027352809730413954909*10^-14
You can see here the difference between the numerator and denominator when you don't have sufficient precision, causing a near singularity.
Some types of objects have special input/output formatting in Mathematica. This includes Graphics, raster images, and, as of Mathematica 8, graphs (Graph[]). Unfortunately large graphs may take a very long time to visualize, much longer than most other operations I'm doing on them during interactive work.
How can I prevent auto-layout of Graph[] objects in StandardForm and TraditionalForm, and have them displayed as e.g. -Graph-, preferably preserving the interpretability of the output (perhaps using Interpretation?). I think this will involve changing Format and/or MakeBoxes in some way, but I was unsuccessful in getting this to work.
I would like to do this in a reversible way, and preferably define a function that will return the original interactive graph display when applied to a Graph object (not the same as GraphPlot, which is not interactive).
On a related note, is there a way to retrieve Format/MakeBoxes definitions associated with certain symbols? FormatValues is one relevant function, but it is empty for Graph.
Sample session:
In[1]:= Graph[{1->2, 2->3, 3->1}]
Out[1]= -Graph-
In[2]:= interactiveGraphPlot[%] (* note that % works *)
Out[2]= (the usual interactive graph plot should be shown here)
Though I do not have Mathematica 8 to try this in, one possibility is to use this construct:
Unprotect[Graph]
MakeBoxes[g_Graph, StandardForm] /; TrueQ[$short] ^:=
ToBoxes#Interpretation[Skeleton["Graph"], g]
$short = True;
Afterward, a Graph object should display in Skeleton form, and setting $short = False should restore default behavior.
Hopefully this works to automate the switching:
interactiveGraphPlot[g_Graph] := Block[{$short}, Print[g]]
Mark's concern about modifying Graph caused me to consider the option of using $PrePrint. I think this should also prevent the slow layout step from taking place. It may be more desirable, assuming you are not already using $PrePrint for something else.
$PrePrint =
If[TrueQ[$short], # /. _Graph -> Skeleton["Graph"], #] &;
$short = True
Also conveniently, at least with Graphics (again I cannot test with Graph in v7) you can get the graphic with simply Print. Here, shown with Graphics:
g = Plot[Sin[x], {x, 0, 2 Pi}]
(* Out = <<"Graphics">> *)
Then
Print[g]
I left the $short test in place for easy switching via a global symbol, but one could leave it out and use:
$PrePrint = # /. _Graph -> Skeleton["Graph"] &;
And then use $PrePrint = . to reset the default functionality.
You can use GraphLayout option of Graph as well as graph-constructors to suppress the rendering. A graph can still be visualized with GraphPlot. Try the following
{gr1, gr2, gr3} = {RandomGraph[{100, 120}, GraphLayout -> None],
PetersenGraph[10, 3, GraphLayout -> None],
Graph[{1 -> 2, 2 -> 3, 3 -> 1}, GraphLayout -> None]}
In order to make working easier, you can use SetOptions to set GraphLayout option to None for all graph constructors you are interested in.
Have you tried simply suppressing the output? I don't think that V8's Graph command does any layout, if you do so. To explore this, we can generate a large list of edges and compare the timings of graph[edges];, Graph[edges];, and GraphPlot[edges];
In[23]:= SeedRandom[1];
edges = Union[Rule ### (Sort /#
RandomInteger[{1, 5000}, {50000, 2}])];
In[25]:= t = AbsoluteTime[];
graph[edges];
In[27]:= AbsoluteTime[] - t
Out[27]= 0.029354
In[28]:= t = AbsoluteTime[];
Graph[edges];
In[30]:= AbsoluteTime[] - t
Out[30]= 0.080434
In[31]:= t = AbsoluteTime[];
GraphPlot[edges];
In[33]:= AbsoluteTime[] - t
Out[33]= 4.934918
The inert graph command is, of course, the fastest. The Graph command takes much longer, but no where near as long as the GraphPlot command. Thus, it seems to me that Graph is not, in fact, computing the layout, as GraphPlot does.
The logical question is, what is Graph spending it's time on. Let's examine the InputForm of Graph output in a simple case:
Graph[{1 -> 2, 2 -> 3, 3 -> 1, 1 -> 4}] // InputForm
Out[123]//InputForm=
Graph[{1, 2, 3, 4},
{DirectedEdge[1, 2],
DirectedEdge[2, 3],
DirectedEdge[3, 1],
DirectedEdge[1, 4]}]
Note that the vertices of the graph have been determined and I think this is what Graph is doing. In fact, the amount of time it took to compute Graph[edges] in the first example, comparable to the fastest way that I can think to do this:
Union[Sequence ### edges]; // Timing
This took 0.087045 seconds.
Suppose I write a black-box functions, which evaluates an expensive complex valued function numerically, and then returns real and imaginary part.
fun[x_?InexactNumberQ] := Module[{f = Sin[x]}, {Re[f], Im[f]}]
Then I can use it in Plot as usual, but Plot does not recognize that the function returns a pair, and colors both curves the same color. How does one tell Mathematica that the function specified always returns a vector of a fixed length ? Or how does one style this plot ?
EDIT: Given attempts attempted at answering the problem, I think that avoiding double reevalution is only possible if styling is performed as a post-processing of the graphics obtained. Most likely the following is not robust, but it seems to work for my example:
gr = Plot[fun[x + I], {x, -1, 1}, ImageSize -> 250];
k = 1;
{gr, gr /. {el_Line :> {ColorData[1][k++], el}}}
One possibility is:
Plot[{#[[1]], #[[2]]}, {x, -1, 1}, PlotStyle -> {{Red}, {Blue}}] &# fun[x + I]
Edit
If your functions are not really smooth (ie. almost linear!), there is not much you can do to prevent the double evaluation process, as it will happen (sort of) anyway due to the nature of the Plot[] mesh exploration algorithm.
For example:
fun[x_?InexactNumberQ] := Module[{f = Sin[3 x]}, {Re[f], Im[f]}];
Plot[{#[[1]], #[[2]]}, {x, -1, 1}, Mesh -> All,
PlotStyle -> {{Red}, {Blue}}] &#fun[x + I]
I don't think there's a good solution to this if your function is expensive to compute. Plot will only acknowledge that there are several curves to be styled if you either give it an explicit list of functions as argument, or you give it a function that it can evaluate to a list of values.
The reason you might not want to do what #belisarius suggested is that it would compute the function twice (twice as slow).
However, you could use memoization to avoid this (i.e. the f[x_] := f[x] = ... construct), and go with his solution. But this can fill up your memory quickly if you work with real valued functions. To prevent this you may want to try what I wrote about caching only a limited number of values, to avoid filling up the memory: http://szhorvat.net/pelican/memoization-in-mathematica.html
If possible for your actual application, one way is to allow fun to take symbolic input in addition to just numeric, and then Evaluate it inside of Plot:
fun2[x_] := Module[{f = Sin[x]}, {Re[f], Im[f]}]
Plot[Evaluate[fun2[x + I]], {x, -1, 1}]
This has the same effect as if you had instead evaluated:
Plot[{-Im[Sinh[1 - I x]], Re[Sinh[1 - I x]]}, {x, -1, 1}]