Array operation not working in Mathematica - wolfram-mathematica

I am trying to perform a calculation in Mathematica 9.0. It is using NSum and works just fine when I use a single value of 't'. The problem is I would like to the calculation for an array of 't'. So I simply changed t = 0.3 to t = {0.3, 0.4} for example. It will now not evaluate with the reason Summand *my equation* is not numerical at point k = 0.
I dont quite understand why though, because it will work if I try a value of 0.3 or 0.4 separately. But I would like to do it over an array of values.
My function is
NSum[(-1)^k/k!*(t/0.6)^(0.6*k + 1), {k, 0, 5000},WorkingPrecision -> 10, NSumTerms -> 5000]
Any help would be appreciated.
Thanks

You can use Table :-
Table[NSum[(-1)^k/k!*(t/0.6)^(0.6*k + 1), {k, 0, 5000},
WorkingPrecision -> 10, NSumTerms -> 5000], {t, {0.3, 0.4}}]
{0.26, 0.30}

Another way..
t={.3, .4}
Function[t,
NSum[(-1)^k/k!*(t/0.6)^(0.6*k + 1), {k, 0, 5000},
WorkingPrecision -> 10, NSumTerms -> 5000], {Listable}][t]
{0.26, 0.30}
This has the advantage of working the same whether t is a list or a single value..

Related

How do I index list elements in For loop in Mathematica?

I do not know the required syntax in Mathematica for printing out multiple 3D plots as intended in the following code.
For[i = 1, i <= accBeta + 1, i++,
ListPlot3D[p3[[All, i]], PlotRange -> All, ColorFunction -> "Rainbow"]
]
Here p3 is a list of lists containing the information while i is my counting index. This doesn't run into errors, but the input is simply ignored. Can you help me out on this issue?
Felix
With some example data
p3 = Table[Sin[k j^2 + i], {i, 0, Pi, Pi/5}, {j, 0, Pi, Pi/5}, {k, 3}];
The following are equivalent
Table[ListPlot3D[p3[[x]], Mesh -> None, InterpolationOrder -> 0,
ColorFunction -> "Rainbow"], {x, Length[p3]}]
Map[ListPlot3D[#, Mesh -> None, InterpolationOrder -> 0,
ColorFunction -> "Rainbow"] &, p3]
You don't actually need a For loop here. For instance you could use Table:
Table[ListPlot3D[p3[[All,i]]], {i, 1, accBeta+1}]
That should print your plots. Hope that's helpful.
There are many related questions on the Mathematica Stack Exchange - typically the answer is not to use a For or Do loop :)

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.

How to plot this function?

I am trying to plot the region $x^{p}+y^{p}\le 1$ in the xy-plane. But when I ran commands like this:
RegionPlot[x^0.7 + y^0.7 <= 1, {x, -500, 500}, {y, -500, 500}]
I always encounter error messages like:
LessEqual::nord: Invalid comparison with -91.0952+125.382 I attempted. >>
I am confused - how can I make mathematican know I am seeking the region in R^{2}, not in C^{2}?
The invalid comparison error is actually not the problem here. RegionPlot[] will plot the region where the expression evaluates to True. The regions where the expression is complex do not evaluate True and regionplot will leave them blank.
The reason you see a fully blank plot is simply that your absolute range is too large. RegionPlot uses a coarse grid by default and misses the small True region all together.
This works (throwing the Invalid comparison as a warning)
RegionPlot[TrueQ[( x^0.7 + y^0.7 <= 1)], {x, -1, 1}, {y, -1, 1},
PlotPoints -> 100]
You can surpress the warning:
Quiet[RegionPlot[TrueQ[( x^0.7 + y^0.7 <= 1)], {x, -1, 1}, {y, -1, 1},
PlotPoints -> 100], {LessEqual::nord}]
Your plotting range is invalid. You're calculating (-500)^0.7, which is a complex number (-45.5509762 + 62.69554i to be specific).
RegionPlot[Table[x^i + y^i <= 1, {i,.1,1,.1}], {x,0,1}, {y,0,1}, Evaluated->True]

difference of speed in making a Table

I was reading a useful post at WRI blog on improving speed of code, and I need help in understanding this one.
Compare these speeds
Timing[
tbl = Table[i + j, {i, 1, 1000}, {j, 1, 1000}];
]
{0.031, Null}
and
Timing[
a = 1000;
tbl = Table[i + j, {i, 1, a}, {j, 1, a}];
]
{0.422, Null}
So it is much faster when putting the actual value for the limit inside the table itself vs outside. The explanation for this, which I am sure it is correct, but I need help in understanding, is that Table is compiled if its limit are numeric vs. not, this is because its Attributes is HoldAll.
But my question is: How would the above actually work, because the limits to Table must, at one point, become numeric anyway? I can't write
Clear[a]
tbl = Table[i + j, {i, 1, a}, {j, 1, a}]
The above gives an error.
So, for me, writing a=1000 outside Table vs. inside, should have made no difference, since without a having a numerical value, Table[] can't do anything. So the replacing of a by the number 1000 must occur at one point of time by evaluator before Table[] can do anything useful, would it not?
In other words, what Table should see, eventually, is {i, 1, 1000}, {j, 1, 1000} in both cases.
So, the way I thought this would happen is this:
Evaluator replaces a by 1000 in the arguments of table
Evaluator calls Table with the result, which is now all numeric.
Table Compiles, and runs faster now.
But what seems to happen is something else. (due to HoldAll ?)
Table takes its arguments, as is. Since it has HoldAll, so it sees a and not 1000.
It does not call Compile since its arguments are not all numbers.
It now generate a table with the a limit, Evaluator evaluates a to 1000
Table is generated now all limits are numeric, but slower now since code is not compiled.
Question is: Does the above sort of what happens? Could someone explain the steps that would have happened to explain this difference in timing?
Also, how would one insure that Table is Compiled in both cases in the above example, even if one uses a variable for the limit? It is not always possible to hardcode the numbers for the table limits, but one must sometime use a variables for these. Should one explicitly use the Compile command? (I do not use Compile directly, since I assumed it is done automatically when needed).
edit(1)
In answer to post by Mike below on finding no difference in timing when using a call.
ClearAll[tblFunc];
Timing[a = 1000;
tblFunc[a_] := Table[i + j, {i, 1, a}, {j, 1, a}];
Developer`PackedArrayQ[tblFunc[a]]
]
gives
{0.031, True}
But that is because a is now the number 1000 INSIDE the function, once it is called. Since M passes things by VALUE.
If we force the call to be by reference, so that a is left unevaluated, then we get
ClearAll[tblFunc];
Timing[a = 1000;
tblFunc[a_] := Table[i + j, {i, 1, a}, {j, 1, a}];
Developer`PackedArrayQ[tblFunc[Unevaluated#a]]
]
now we see the expected result, since now a is still symbolic INSIDE the function, we are back to square one, and now it is slow, since not packed. And since it is not packed, Compile is not used.
{0.437, False}
edit(2)
Thanks to everyone for the answers, I think I learned allot from them.
Here is an executive summary, just to make sure I got everything ok.
edit(3)
Here are links I have specially related to hints to use to making Mathematica code runs faster.
http://library.wolfram.com/howtos/faster/
http://blog.wolfram.com/2011/12/07/10-tips-for-writing-fast-mathematica-code/
https://stackoverflow.com/questions/4721171/performance-tuning-in-mathematica
Using Array and Table Functions in Mathematica. Which is best when
So this is what I think is happening. The reason why you see the slow down between a numeric and a symbolic limit on Table is due to the fact that you do a double index. Each sub-table (e.g. going over all indices j for a fixed index i) is constructed separately and when the limit is symbolic there is an extra step involved in figuring out that limit before constructing each sub table. You can see this by examining, e.g.
Trace[a = 3;
tbl = Table[i + j, {i, 1, a}, {j, 1, a}];
]
David gives a good example for why you would want to do this check for every sub list. As to why Mathematica cannot figure out when this check is not needed I have no clue. If you only have one index to sum over there is no difference in speed between the symbolic and numeric version
Timing[tbl = Table[i + j, {j, 1, 1000}];]
{0.0012, Null}
Timing[a = 1000;
tbl = Table[i + j, {j, 1, a}];
]
{0.0013, Null}
To answer your follow up regarding speed; making tbl a function is faster for both numeric and symbolic limits.
Timing[a = 1000;
tblFunc[a_] := Table[i + j, {i, 1, a}, {j, 1, a}];
tblFunc[a];
]
{0.045171, Null}
vs.
Timing[tbl = Table[i + j, {i, 1, 1000}, {j, 1, 1000}];]
{0.066864, Null}
Timing[a = 1000;
tbl = Table[i + j, {i, 1, a}, {j, 1, a}];
]
{0.632128, Null}
You gain even more speed if you intend to reuse the tbl construction.
b=1000;
Timing[tblFunc[b];]
{0.000013, Null}
The key things to monitor, as others have mentioned, are packing and list length. I actually don't see the differences that Timo reports:
ClearAll[tblFunc];
Timing[a = 1000;
tblFunc[a_] := Table[i + j, {i, 1, a}, {j, 1, a}];
Developer`PackedArrayQ[tblFunc[a]]]
{0.077706, True}
vs
ClearAll[tbl];
Timing[
tbl = Table[i + j, {i, 1, 1000}, {j, 1, 1000}];
Developer`PackedArrayQ[tbl]]
{0.076661, True}
ClearAll[tbl];
Timing[a = 1000;
tbl = Table[i + j, {i, 1, a}, {j, 1, a}];
Developer`PackedArrayQ[tbl]]
{1.02879, False}
So for me the only difference is if the list is packed. Whether it is a function makes no difference to timing on my set up. And as expected when you switch off autocompilation the timings are the same for all of the above because no packing occurs:
SetSystemOptions["CompileOptions" -> {"TableCompileLength" -> Infinity}];
{1.05084, False}
vs
{1.00348, False}
{1.01537, False}
reset the table autocompile length:
SetSystemOptions["CompileOptions" -> {"TableCompileLength" -> 250}]
This is slightly OT, but for speed here you might want to avoid using the item-by-item processing that's implicit in using Table. Rather, use Outer. Here's what I'm seeing on my system:
Timing[Outer[Plus, Range[5000], Range[5000]];]
{0.066763,Null}
Timing[Table[i + j, {i, 1, 5000}, {j, 1, 5000}];]
{0.555197,Null}
Quite a dramatic difference.

automatize a mathematic procedure: I need industrial amouts of results, and I get one

I've the following simple code in mathematica that is what I want to a single output. But I want to get hundreds or thousands of it. How can I do?
Clear["Global`*"]
k = 2; Put["phiout"]; Put["omegadiffout"];
Random[NormalDistribution[0, 0.1]];
For[i = 1, i < 31,
rnd[i] = Random[NormalDistribution[0, 0.1]]; i++]
Table[rnd[i], {i, 1, 30}]
For[i = 1, i < 30,
rnddf[i] = rnd[i + 1] - rnd[i]; i++
]
diffomega = Table [rnddf[i], {i, 1, 29}];
Table[
Table [rnddf[i], {i, 1, 29}], {j, 1, 100}];
PutAppend[Table[
diffomega, {j, 1, 100}] , "diffomega"]
eqs0 = Table [
k*phi[i + 1] + k*phi[i - 1] - 2*k*phi[i] - rnddf[i] == 0, {i, 1,
28}];
eqs1 = eqs0 /. {phi[0] -> phi[30], phi[31] -> phi[1]};
Sum[phi[i], {i, 1, 29}];
eqs2 = Append[eqs1, - phi[1] - phi[27] - 3 phi[29] == 0];
eqs3 = eqs2 /. {phi[30] -> -Sum[phi[i], {i, 1, 29}]};
vars = Table [phi[i], {i, 1, 29}];
eqs = NSolve[eqs3, vars];
PutAppend[diffomega, eqs , "phiout"]
This put on file "phiout" and "omegadiffout" only the last value. I need hundreds of them. For each random generations I need an output.
Thanks in advance
The first thing you need to do, #Paulo, is tidy up your Mathematica so that you, and we, can see the wood for the trees. For example, your 8th statement:
Table[
Table [rnddf[i], {i, 1, 29}], {j, 1, 100}];
makes a large table, but the table isn't assigned to a variable or used in any other way. There seem to be other statements whose results aren't used either.
Next you should abandon your For loops and use the Mathematica idioms -- they are clearer for we who use Mathematica regularly to understand, easier for you to write, and probably more efficient too. Your statements
For[i = 1, i < 31,
rnd[i] = Random[NormalDistribution[0, 0.1]]; i++]
Table[rnd[i], {i, 1, 30}]
For[i = 1, i < 30,
rnddf[i] = rnd[i + 1] - rnd[i]; i++
]
diffomega = Table [rnddf[i], {i, 1, 29}];
can, if I understand correctly, be replaced by:
diffomega = Differences[RandomReal[NormalDistribution[0,0.1],{30}]];
Always remember that if you are writing loops in Mathematica you are probably making a mistake. The next change you should make is to stop using Put and PutAppend until you can build, in memory, at least a small example of the entire output that you want to write. Then write that to a file in one go with Save or Export or one of the other high-level I/O functions.
When you have done that, edit your code and explain what you are trying to do and I, and other SOers, will try to help further. Unfortunately, right now, your code is so un-Mathematica-al that I'm having trouble figuring it out.

Resources