Skip to main content

Posts

Showing posts from July, 2016

list manipulation - Mapping over a piecewise function

This is a followup to a question I posted earlier today . Suppose you have a piecewise function such as "snap=max[x,0]= x if x>0, 0 otherwise". Then you would think that it must be straightworward to apply a function to this, i.e. to obtain "f[x] if x > 0, f[0] otherwise". My intuition is that I should be able to say "f[snap]", but this doesn't work. The best I can do (after help from AccidentalFourierTransform ) is quite complicated: snap = PiecewiseExpand[Max[0, x]] MapAt[f[#] &, Map[MapAt[f[#] &, 1], snap, {2}], -1] This produces the desired result, but it seems strange that I need to do this. Is there a more straight-forward solution? Answer pwMap1[f_] := MapAt[f, #, {{1, All, 1}, {2}}] &; pwMap1[f]@snap // TeXForm $\begin{cases} f(x) & x>0 \\ f(0) & \text{True} \end{cases}$ Also: pwMap2[f_] := Internal`ToPiecewise[#, f /@ #2] & @@ Internal`FromPiecewise[#] &; pwMap2[f]@snap == pwMap1[f]@snap True

plotting - How do I show intersecting points of three functions in 3D?

I'm trying to plot the following 3 functions: $f_1 = x^2 + y - 37 = 0$ $f_2 = x - y^2 - 5 = 0$ $f_3 = x + y - 3 - z = 0$ Plot3D[{x^2 + y - 37, x - y^2 - 5, x + y + z - 3}, {x, -10, 10}, {y, -10, 10}, {z, -10, 10}] but it gives me a error. How do I fix this? Also is there any way to show graphically where the 3 functions intersect, say with a red dot or something? Thank you for the help in advance. Answer s = Solve[{x^2 + y - 37 == 0, x - y^2 - 5 == 0, x + y + z - 3 == 0}]; Two solutions. Show[ContourPlot3D[{x^2 + y - 37 == 0, x - y^2 - 5 == 0, x + y + z - 3 == 0}, {x, -10, 10}, {y, -10, 10}, {z, -10, 10}, ContourStyle ->({#, Opacity[0.8]} &) /@ {Green, Yellow, Orange}], Graphics3D[{Red, Sphere[{x, y, z} /. s[[#]]] & /@ {1, 2}}]]

numerics - How are Accuracy and Precision related Mathematica for a given operation?

The common understanding for Accuracy and Precision in English language is given by this figure. Inspired by this question I have a follow up question relating Accuracy and Precision in Mathematica and Wolfram language. How do we understand the relationship between Accuracy and Precision in the following example? Accuracy[ SetPrecision[ SetAccuracy[ 12.3 , 20], 15] ] 13.9101 Precision[ SetAccuracy[ SetPrecision[ 12.3 , 20], 15] ] 16.0899 Where is this 13.9101 and 16.0899 coming from, exactly. Given an operation, such as Subtract , Plus or Times . How do we predict the Accuracy and Precision of the outcome? Precision[ Times[ SetPrecision[10, 3] , SetPrecision[1, 7] ]] 2.99996 Precision[ Plus[ SetPrecision[10, 3] , SetPrecision[1, 7] ]] 3.04139 Accuracy[ Plus[ SetAccuracy[10, 3] , SetAccuracy[1, 7] ]] 2.99996 Accuracy[ Times[ SetAccuracy[10, 3] , SetAccuracy[1, 7] ]] 2.99957 Answer Precision is the principal representation of n...

calculus and analysis - How can I simplify a triple integral with exponentials?

I want to simplify the following triple integral with exponential terms. \begin{equation} \int_0^\infty\int_0^\infty \int_0^\infty \frac{1}{R\,G} e^{-p(1+R\,a)-q\, b \frac{1+R\, a}{1+G\, x}}\, e^{\frac{-a}{R}}\, e^{-b}\, e^{\frac{-x}{G}} db\,dx \,da \end{equation} where I assume $R>0$, $G>0$, $p>0$ and $q>0$. Using both commands Simplify and FullSimplify , Mathematica after hours didn't get any solution. I tried two versions of Mathematica , 7 and 10, but nothing changes. Is there any smart way to make a simplification? Here is my Mathematica code: Simplify[ Integrate[ Integrate[ Integrate[ 1/(R G) Exp[-p(1 + R a) - b q ((1 + R a)/(1 + G x))] Exp[-a/R] Exp[-b] Exp[-x/G], {b, 0, ∞}], {x, 0, ∞}], {a, 0, ∞}, Assumptions -> G > 0 && R > 0 && p > 0 && q > 0 ]] Answer With using number of assumptions, and breaking thing step by step: (I do things step by step, just to see where the...

performance tuning - How can I generate a $2n$-point moving maximum of a list as efficiently as MaxFilter?

This is based on the prior question, Moving maximum function? , where @rasher provided two winning solutions ( i.e. clearly the most efficient): MaxFilter[list, 1] and Max /@ Transpose[{Rest[Append[#, 0]], #, Most[Prepend[#, 0]]}] &[list] Taking the same example list, {5, 6, 9, 3, 2, 6, 7, 8, 1, 1, 4, 7} I'd like to be able to specify a window $w$ such that a rolling maximum starts at index $w$, generating, for example for $w=5$ (lined up on purpose): {9, 9, 9, 8, 8, 8, 8, 8} That's not too hard; as @TylerDurden hinted, we can simply use MaxFilter with range $(w-1)/2=2$ and drop each end ("shifting," as he imagined): w=5; Drop[Drop[MaxFilter[list, (w - 1)/2], (w - 1)/2], -(w - 1)/2] (* {9, 9, 9, 8, 8, 8, 8, 8} *) But of course, this can't be done with an even number $w$. So, giving up, I decided to try to generalize @rasher's second solution— i.e. staggering $w$ copies of the list (in his case, essentially hardcoded to $w=3$) and getting m...

plotting - Modular surface of tri-focal Cassini curve ContourPlot3D missing feet

I am wondering why the following fails to cover the surface at points near $k = 0$. c[z_] := (z + 1) (z - 1) (z + 1 + I); ContourPlot3D[Abs[c[x + I y]] == k^3, {x, -2.5, 2}, {y, -2, 2}, {k, 0, 1.75}, Background -> White, AxesLabel -> {"x", "y", "k"}] Furthermore, when the left hand side is complex expanded and the equation is rearranged with $2xy+k^3$ on the right, the curve looks significantly different, with one large and one small foot, both touching at zero. Why is that? Answer ContourPlot3D is not very good at resolving thin features, because it only knows that the feature exists when one of the sampling points happens to land inside it. In general, one thing you can do is to increase PlotPoints , which improves the plot but takes a very long time. ContourPlot3D[ Abs[c[x + I y]] == k^3, {x, -2.5, 2}, {y, -2, 2}, {k, 0, 1.75}, Background -> White, AxesLabel -> {"x", "y", "k"}, PlotPoints -> 20] In this ...

functions - Double application of NIntegrate produces unexpected error messages

In the course of trying to answer 69601 , I encountered unexpected error messages. In highly simplified form, NIntegrate[NIntegrate[z y, {y, 0, 10}], {z, 0, 10}] produces repeated messages, NIntegrate::inumr: The integrand y z has evaluated to non-numerical values for all sampling points in the region with boundaries (0 10). >> before returning the correct answer, 2500 . Thus, the error messages seem to be harmless, apart from consuming time. Nonetheless, I would like understand their source and eliminate them by means other than Quiet . The option Method -> {Automatic, "SymbolicProcessing" -> False} reduces the number of messages to one, which is a step in the right direction. Suggestions? Answer The issue is that the interior integral tries to evaluate first and has a symbolic z . This fails and returns unevaluated before being passed to the outer integral. The two solutions that come to mind would be to call NIntegrate as a double integral. NIntegrate[z*y,...

system - How to make the variables in $init.m$ not impact the autocompletion

The autocompletion is very convient in Mathematica ,but it will make one annoying sometimes when you have a ton variables.I give a scene I encounter.I usually make many custom functions in my init.m ,for example System`testFunction[variablea_]:=Module[{variableb=variablea},variableb+1] http://o8aucf9ny.bkt.clouddn.com/2016-06-25-01-06-52.png But when I launch my Mathematica as soon as there are many variables prompt to auto-autocomplete.like this So my question is how to make the variables in init.m not impact the autocompletion Answer Don't put symbols you don't want to show up in auto-completion into the Global` context. Use the same mechanism you would for a package. myfun; (* create in Global` *) Begin["MyPrivateInitContext`"] myfun[x_] := Module[{y=x^2}, y^2] End[] I noticed you are putting your function into the System` context. This seems like a bad idea. The System` context is for builtins. What I do personally is that I create a complete package and lo...

social media - Import tweets from Twitter

Robert Raguet-Schofield in the Mathematica Blog introduced a way to import tweets from Twitter into Mathematica . I attempted to use this method. I started with this line of code: xml = Import["https://twitter.com/statuses/user_timeline.xml?screen_name=WolframResearch"] and received this message: FetchURL::httperr: The request to URL https://twitter.com/statuses/user_timeline.xml?screen_name=WolframResearch was not successful. The server returned the HTTP status code 404 ("Not Found"). Then I tried this xml = Import["https://twitter.com/WolframResearch"]a and this time I got some output. But when I continue the procedure to extract the tweets with this line tweets = Cases[xml, XMLElement["text", _, {s_String}] :> s, ∞] I get an empty set. How can I import tweets into Mathematica in an effective way, given I am not a familiar with Apachi?

programming - Why does Mathematica choose the second function definition?

While working on a solution to this question I've come across a case where I simply don't understand Mathematica's behaviour. I've got the following definitions: PatternImplies[(x:(Verbatim[Blank] |Verbatim[BlankSequence] |Verbatim[BlankNullSequence]))[h_],x[]]:=True (*CatchAll rule*) PatternImplies[_,_]:=Maybe; Now I try this: PatternImplies[_Integer,_] (* ==> Maybe *) I would have expected True . My first thought was that I probably got the pattern wrong, so I tested: MatchQ[PatternImplies[_Integer,_], PatternImplies[(x:(Verbatim[Blank] |Verbatim[BlankSequence] |Verbatim[BlankNullSequence]))[h_],x[]]] (* ==> True *) In other words, the pattern matches. Moreover, looking at Downvalues I see that the special rule is indeed stored before the catch-all rule. So why does Mathematica chose the second definition (and more importantly, what can I do about it?) Answer As far ...

performance tuning - How to speed up calculation of this equation (FindRoot)

I have come up with the following functions, and I need to calculate a value, in order to have a condition valid. In my problem, all data are given, and I need to calculate variable l. I am using findroot, and I give an initial value of 25 (plausible assumption) in order to get what I need. Although my calculation is correct, it is really time consuming (I am using an i7 -3720 qm) and it takes almost 8-9 seconds. My question is, how can I speed up evaluation speed. f1[x_, y_] := PDF[NormalDistribution[l, 3.975], x]* PDF[NormalDistribution[53.559 - l, 3.975], y]; p = (1 - Sum[f1[i, i], {i, 0, 50}])/(1 - Sum[f1[i, i], {i, 0, 50}]*1.4317884120211488); f2[x_, y_] := If[x == y, f1[x, y]*1.4317884120211488`, f1[x, y]/p]; A = SessionTime[]; sexpNEW = FindRoot[Sum[f2[i, j], {i, 0, 50}, {j, 0, i - 6.5}] == 0.4605263157894738, {l, 25}] B = SessionTime[]; My results: {l->29.8104} { speed:,8.6508650,seconds} consider the following example, which is based on my previous, but thi...

How to partition a list in a specific way

I have a list: a = {{1, 2, 3, 4, 1, 2, 3, 4}, {5, 6, 7, 8, 5, 6, 7, 8}}; Using Partition and Map I get: Partition[#, 4]& /@ a {{{1, 2, 3, 4}, {1, 2, 3, 4}}, {{5, 6, 7, 8}, {5, 6, 7, 8}}} And now, I would like to get a list which looks like: {{{{1, 2},{3, 4}}, {{1, 2},{3, 4}}}, {{{5, 6},{7, 8}}, {{5, 6},{7, 8}}}} I tried to play around with Partition and Map , but I did not manage to create such a list. Of course there are easy ways to do it using Do loops and AppendTo , but I very much need to avoid Do loops. Does anybody see the way to create the list? Answer There is a new function in Mathematica 9 - ArrayReshape : ArrayReshape[a, {2, 2, 2, 2}] {{{{1, 2}, {3, 4}}, {{1, 2}, {3, 4}}}, {{{5, 6}, {7, 8}}, {{5, 6}, {7, 8}}}}

mathematical optimization - NMinimize to optimize function Module

I am using Nminimize for simulation based optimization. I define the objective function (simulation with a variable "a") as a module to be used in the minimization. What I have found is if I do not print the function value (f[a]) using the EvaluationMonitor, NMinimize outputs 1000s of iterations of possible values for "a" extremely quickly without running the corresponding simulation run (because if it runs simulations, it will need few seconds for each simulation run and can not do 1000s of simulations in no time). However, when I include "f[a]" in the evaluation monitor, NMinimize runs the simulation for each possible value of "a" it outputs, but is disconnected to the optimization process. This is evident because NMinimize does not converge even after 1000s of iterations, when there are only 10 possible values "a" can take and I know the minimum occurs at "a"=10. Will someone help me understand what I am missing? demand[n_...

equation solving - Finding unit tangent, normal, and binormal vectors for a given r(t)

For my Calc III class, I need to find $T(t), N(t)$, and $B(t)$ for $t=1, 2$, and $-1$, given $r(t)=\{t,t^2,t^3\}$. I've got Mathematica , but I've never used it before and I'm not sure how to coerce it into solving this. (My professor told us to use a computer, as it starts getting pretty nasty around $T'(t)$. By hand, $$T(t)=\frac{1}{ \sqrt{(1+4t^2+9t^4})}\{1,2t,3t^2\}$$ I've tried defining r as stated above and using D , Norm , and CrossProduct . However, I get a bunch of Abs in my outputs (am I missing an assumption?). Additionally, I can't seem to google up how to ask Mathematica to sub in a specific value for $t$, once I get the equations worked out properly. Answer Mathematica wouldn't be much helpful if one applied only formulae calculated by hand. Here we demonstrate how to calculate the desired geometric objects with the system having a definition of the curve r[t] : r[t_] := {t, t^2, t^3} now we call uT the unit tangent vector to r[t] . Sin...

calculus and analysis - BSplineFunction derivatives wrong if using weights?

Bug introduced in 7.0 and persisting through 12.0 or later In my work, I make heavy use of non-uniform rational B-spline (NURBS) functions, defined using the function BSplineFunction[] with the option defining weights . I never before questioned the results given by Mathematica , but it seem that I discovered something that seems like a bug. Let's use a simple example : a quarter of circle. The degree, knot vector, control point vector and weights used for this are : d = 2; kV = {0, 0, 0, 1, 1, 1}; P = {{0, 0}, {0, 1}, {1, 1}}; W = {1, 1/Sqrt[2], 1}; I defined the two parametric functions x and y this way : x[t_] := BSplineFunction[P[[All, 1]], SplineWeights -> W, SplineDegree -> d, SplineKnots -> kV][t]; y[t_] := BSplineFunction[P[[All, 2]], SplineWeights -> W, SplineDegree -> d, SplineKnots -> kV][t]; The results obtained are perfect, {x[t], y[t]} is an exact quarter of circle. The problem is when I want to have the derivatives of x and y . Her...

plotting - How to make Joined skip missing data points

I have a set of data taken on sequential days, but some points are missing. I'd like to make a joined date list plot, where the points are not joined across the missing point.The following example illustrates the desired result. data1 = { {{2013, 7, 1}, 1}, {{2013, 7, 2}, 5}, {{2013, 7, 3}, 2}, {{2013, 7, 4}, 4}, {{2013, 7, 6}, 2}, {{2013, 7, 7}, 6} }; data2 = { {{2013, 7, 1}, 6}, {{2013, 7, 2}, 2}, {{2013, 7, 3}, 4}, {{2013, 7, 4}, 1}, {{2013, 7, 5}, 7}, {{2013, 7, 6}, 1}, {{2013, 7, 7}, 4} }; DateListPlot[{ data1[[1 ;; 4]], data1[[5 ;; 6]], data2[[ ;; ]] }, PlotStyle -> {Blue, Blue, Red}, Joined -> True] Note that data1 is missing a point on July 5. In practice I'm doing this with multiple data sets, with hundreds of points, so breaking it apart and manually assiging plotstyle like I have here is not viable. How can I make Joined skip missing points? Answer You can do this pretty cleanly with TemporalData . Setting the Method to None ensures no interpolation will ...

function construction - Lazy lists of Tuples and Subsets

I'm trying to build a lazy list that evaluates the n'th m-tuple or subset of a given list using Mathematicas ordering without calculating all the Tuples. The purpose is to allow for example the traversal of very large spaces of tuples without fist having to calculate the complete space of tuples. So far I have defined a function that calcluates which elements goes where for the n'th tuple: tupleIndexes[l_, t_, n_] := Table[Mod[Quotient[n - 1, l^m] + 1, l, 1], {m, t - 1, 0, -1}] And have used this to define a lazy list by defining a SubValue for when Part is applied. lazyTuple /:Part[lazyTuple[list_, t_], n_Integer] /; 0 list[[tupleIndexes[Length[list], t, n]]] The result is that lazyTuple[{1,2,3,4},2] remains unevaluted but lazyTuple[{1,2,3,4},2][[2]] returns {1,2} as expected. For testing I've defined a function to iterate through the list and return them all: lazyTuple /: Length[lazyTuple[list_, t_]] := Length[list]^t lazyTuple /: lazyTakeAll[a_lazyTuple] /; (N...

run python with package numpy in mathematica

For example, if I have a python script called simple.py contains as simple as a=1 print(a) then RunProcess[{"python", "E:\\w\\simple.py"}] is ok and gives 0, "StandardOutput" -> "1 ", "StandardError" -> ""|> However, if I edit simple.py as import numpy as np a=np.array([1,2]) print(a) then RunProcess[{"python", "E:\\w\\simple.py"}] gives 1, "StandardOutput" -> "", "StandardError" -> "Traceback (most recent call last): File \"E:\\w\\WORK\\python\\learning\\simple.py\", line 1, in \ import numpy as np File \"D:\\IntelPython35\\lib\\site-packages\\numpy\\__init__.py\"\ , line 158, in from . import add_newdocs File \"D:\\IntelPython35\\lib\\site-packages\\numpy\\add_newdocs.\ py\", line 13, in from numpy.lib import add_newdoc File \"D:\\IntelPython35\\lib\\site-packages\\numpy\\lib\\__ini...

front end - How can I clean up a notebook?

By cleaning up a notebook, I mean how can I hide all the codes in the notebook so that the end-users can't see it? I saw Eric Schulz's famous interactive calculus textbook, the users can't see the code, and there is no cell brackets on the right hand side of the CDF. Answer Update I have incorporated Kuba's improvement into the code. Here is how I would do it. In a working notebook (not the target notebook) put the following code. With[{nb = target}, SetOptions[nb, ShowCellBracket -> False]; SetOptions[#, CellOpen -> False] & /@ Cells[nb, CellStyle -> "Input"];] With[{nb = taget}, SetOptions[nb, ShowCellBracket -> True]; SetOptions[#, CellOpen -> True] & /@ Cells[nb, CellStyle -> "Input"];] The first code cell will do the clean-up. The second lets you undo it if that becomes necessary. Now in the target notebook evaluate EvaluationNotebook[] This will return a notebook object which will look something like $\qquad$...

syntax - Defining a function with parameters as variables

I have an expression V = (a[1] + a[2])b[1] . How would I define a function of a[1] , a[2] and b[1] ? I'm looking for something like this f[a[1]_,a[2]_,b[1]_]=(a[1] + a[2])b[1] but Mathematica isn't satisfied with that definition. Answer One way to do this, most likely not the most elegant, is to rename variables of the form a[n] temporarily. Suppose v = (a[1] + a[2]) b[1] . Then define f[a1_, a2_, b1_] := Evaluate[v /. {a_[n_] :> ToExpression[ToString[a] ToString[n]]}] With this definition you get the desired result if you evaluate f[a[1],a[2],b[1]] .

numerics - Machine Epsilon

I'm trying to evaluate the machine epsilon of my computer (see below). I wrote this: eps = 1.0; p = 0; While[(1.0 + eps) > 1.0, eps = eps/2.0; p += 1]; eps p eps*2 and got: 1.42109*10^-14 46 2.84217*10^-14 which is not what I expected ( IEEE754 ). So I did this EngineeringForm[1.0 + 2 * eps, 20] EngineeringForm[1.0 + eps, 20] EngineeringForm[1.0 + (eps/2.0), 20] EngineeringForm[1.0 + (eps/4.0), 20] EngineeringForm[1.0 + (eps/16.0), 20] EngineeringForm[1.0 + (eps/32.0), 20] and got that: 1.000000000000028 1.000000000000014 1.000000000000007 1.000000000000004 1.000000000000001 1. which seems to contradict the termination condition of the 'while' loop. So I would like to understand what's going on under Mathematica's hood. I tried to look for some information on Mathematica's internal float representation without success. Any help to explain these results is welcome. I'm sorry if my question is a bit vague. Eric Context: SystemInformationData[{"Kerne...

mathematical optimization - Find Maximum doesn't seem to work

r[t_] = {3 Cos[(3.3)*π*t], Sin[4*π*t] + 4 t}; n[t_] = Norm[r'[t]*r''[t]]/Norm[r'[t]]; Plot[n[t], {t, 0, 1}, PlotLabel -> "Normal Component of Acceleration vs Time", AxesLabel -> {"Time (hours)", "Acceleration (km/h^2)"}] FindMaximum[n[t], {t, 0}] I'm trying to find the maximum of the curve n[t] , but when using FindMaximum , the value that is returned clearly doesn't fit the graph.

plotting - Plot the solution from DSolve

I'm trying to solve a differential equation as in the following code: FullSimplify[DSolve[x'[t] == a + b E^(g t) + (c + d E^(-g t)) x[t], x[t], t]] which generates Now, I would like to plot it with specific parameter values assigned, for example: a = 1; b = 2; c = 3; d = 4; g = 0.1; A = 1 where I replaced the integration constant c_1 with A . Here is my code for plotting x[t] : a = 1; b = 2; c = 3; d = 4; g = 0.1; A = 1 x[t_] := E^(-((d E^(-g t))/g) + c t) (A + Integrate[E^((d E^(-g K[1]))/g - c K[1]) (a + b E^(g K[1])), {K[1], 1, t}]) Plot[x[t], {t, 1, 10}] It runs forever. To check whether Mathematica is doing calculations, I tried x[1] and it yielded 3.83926*10^-15 which is nice. But when I tried x[2] I got It seems Mathematica cannot compute the integral unless the integration region is $\int_1^1$ . Is this because the integrand is too complicated? Is there any way to let Mathematica compute it? Thanks! Answer It runs forever, since you used := instead of = so it was ...

graphics - Exporting an image so that the PlotRange has a fixed size in the output

I am writing a document that involves a table of plots, of an array of quantities ($f$ and $g$, say) against an array of variables ($x$ and $y$, say), and which I would like to present in the following form: I have produced this minimal working example via the following Mathematica code, fraction = 0.54; var[1] = "x"; var[2] = "y"; var[3] = "x"; var[4] = "y"; fun[1] = "f"; fun[2] = "f"; fun[3] = "g"; fun[4] = "g"; Grid[Partition[#, 2]] &@ Table[ figure[n] = Plot[ x^n , {x, 0, 1} , ImageSize -> If[n == 1 || n == 3, fraction 370, (1 - fraction) 370] , Frame -> True , FrameLabel -> {var[n], fun[n]} ,,Epilog->{Inset[Text[Evaluate["(" {"a","b","c","d"}[[n]] ") " fun[n] "=\!\(\*SuperscriptBox[\(" var[n] "\), \(" ToString[n] "\)]\)"]], Scaled[{0.5,0.97...

list manipulation - How to create overlapped block matrices and simplify the result

This is sort of a duplicate of Creating overlapped block matrices , but the question wasn't fully answered since the OP never returned to clarify. I am using Kuba's answer for FEM, but I have been unable to get it to work properly. The problem is that the block matrix isn't being simplified even when the arrays we are working with are known (not arbitrary). Below is sample code. I have used examples for a , b and c , but in my actual code the matrices are larger and much more complicated. a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; b = {{3, 2, 7}, {2, 0, 3}, {4, 1, 2}}; c = {{5, 1, 4}, {4, 5, 8}, {9, 1, 6}}; n = {3, 3}; arrays = Array[#, n] & /@ {a, b, c}; (*arrays to work with*) app[a1_, a2_, overlap_: 1] := With[{dim = Dimensions@a1}, ArrayPad[a1, {0, n[[1]] - overlap}] + ArrayPad[a2, Transpose@{dim - overlap, {0, 0}}]]; Fold[app, First@arrays, Rest@arrays] // MatrixForm Notice how Mathematica returns...

files and directories - What kind of check does DirectoryQ exactly perform?

I'm using Mathematica 9.0.1 on Windows XP and my drive letters are assigned as follows: C: and D: are hard local disks, while E: is assigned to some removable media. Now, the situation is as follows DirectoryQ[# ":\\"] & /@ {"c", "d", "e"} returns {True,True,True} , even when an optical disk isn't in the drive. To outflank the problem I use a directoryQ function, defined in the code below. However, it obviously fails against a full hard disk or when I don't have write access. Therefore, I' m wondering about the kind of check DirectoryQ basically performs. Is there a better solution to fix the problem? directoryQ[unit_]:=Module[ {root,file,ret}, ret=False; root=unit ":\\"; file = FileNameJoin[{root, "testFile.txt"}]; If[ DirectoryQ[root], Quiet[Export[file,"test","Text"]]; If[ FileExistsQ[file], ...

functions - How to Reap data from a ScheduledTask?

Here is an amusing little function mapped over a range just to iterate it. It ignores its argument and works entirely by side-effecting a global variable: n$ = 1; Map[(n$ = (n$++) + n$) &, Range[5]] {3, 7, 15, 31, 63} Here is a version of the same thing, just using Reap and Sow : n$ = 1; Reap[Map[Sow[n$ = (n$++) + n$] &, Range[5]]][[1]] {3, 7, 15, 31, 63} Here is a version that evaluates the function in an asynchronous task, capturing the result in a Dynamic (you'll have to key it in to a notebook, or evaluate the SEUploader (courtesy of @halirutan) notebook I linked at the end of this post, to see the variable n$ updating dynamically): n$ = 1; Dynamic[n$] RunScheduledTask[n$ = (n$++) + n$, {0.25, 5}]; 63 Clean up the task: RemoveScheduledTask[ScheduledTasks[]] Now, here is an attempt to also capture the results in a Reap (notice no semicolon at the end; I want to see the results of the Reap as well as to see the Dynamic ): n$ = 1; Dynamic[n$] Reap[RunScheduledTask[S...

Am I missing anything? Solving Equations

I want to know what $ a^4+b^4+c^4 $ would be when $ a+b+c=1, a^2+b^2+c^2=2, a^3+b^3+c^3=3. $ I tried Solve[{a + b + c == 1, a^2 + b^2 + c^2 == 2, a^3 + b^3 + c^3 == 3}, {a, b, c}] a^4 + b^4 + c^4 /. {a -> ... } I copied and pasted one instance from the result of Solve[] into {a -> ...} The solution and the result of Simplify[] of it was not quite what I expected. So as a test, I tried a+b+c /. {a -> ...} Still it was strange, it didn't come up with 1 which is obvious correct answer. So am I missing anything here? Is there any better way? Answer Solve your equations with respect to another variable d == a^4 + b^4 + c^4 eliminating given ones Solve[{ a + b + c == 1, a^2 + b^2 + c^2 == 2, a^3 + b^3 + c^3 == 3, a^4 + b^4 + c^4 == d}, {d}, {a, b, c}] {{d -> 25/6}} This tutorial will be helpful Eliminating Variables . Edit For the sake of completeness we add another methods of dealing with the problem. Let's point out even simpler way than the first on...

Series and that old ivar error

I am trying to compare plots of the function (1+x)^{1/3} and its power series. The code for the power series generates an error message referring to an invalid variable: 'General::ivar: -1.09993 is not a valid variable."' This message occurred with a minimum x of -1.1. Whatever value is given to the minimum x, the error message is always .00007 or .00008 greater. Yet it continues and plots the curve to maximum x. I would like to know the reason for the error message. A previous similar question by @fasttouch "Plot Series output?" was closed as off-topic. The apparent correct answers were to apply Normal[], which I have done, and Evaluate[], which here seems to have no effect, as the curves with and without it coincide. If there is a trivial syntax error, it would not surprise me, but I can't see it, nor does the answer appear to be easily found in the documentation. I have Mathematica 8. I am also wondering why I need to reference the series with an index in ...

How to convert string to integer list?

Saying we have a string: "1 2 3 4 5 6" I want to convert this to integer list. First I do: In[82]:= str = StringReplace["1 2 3 4 5 6", " " -> ","] // List Out[82]= {"1,2,3,4,5,6"} No I need to convert Out[82] to be just {1,2,3,4,5,6} . Any idea? Thanks! Answer res = ToExpression@StringSplit["1 2 3 4 5 6", " "] {1, 2, 3, 4, 5, 6} Head /@ res {Integer, Integer, Integer, Integer, Integer, Integer}

memory - calculating subsets of a matrix (L=40X40)

I need to calculate all $k$-possible subsets$(k:1,L)$ of matrix with size $L$. I am using subset function as following, L = 10; Do[ t = L!/(k! (L - k)!); tstmat = RandomReal[L, {L, L}]; config = Subsets[Range[Length@tstmat], {k}]; Print[{k, t}] , {k, 1, L} ]; this is working fine up to $L=24$, but for big sizes I am running into memory issues, L | mem 25 | 2.152 G 26 | 3.600 G 27 | 6.470 G 28 | 12.418 G 29 | 23.641 G I am assuming the huge memory is related to part of code where it's calculating the different subsets and keeps all of different configuration, for example for size L=30 and L=40 this becomes on the order of 10^9 and 10^12 sub-lists, respectively. Is there any way to decrease the memory, for example by keeping subsets once at a time? Or maybe is there any other function in Mathematica to calculate the all possible subsets?

plotting - Histogram scale error when using DistributionChart

I'm a novice Mathematica user that is having some problems using the HistogramDensity function in a DistributionChart. My observations are heavily skewed to one category and the height of the other categories are larger than the number of observations should imply. Any ideas? Here's a stylized example of my problem: data = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4} DistributionChart[data, ChartElementFunction -> ChartElementDataFunction["HistogramDensity", "Bins" -> 4]] Answer As @DavidSkulsky commented the problem is due to the scaling inside ChartElementDataFunction["HistogramDensity"] . A workaround is to use a custom ChartElementDataFunction . For example, the following transforms the Rectangle s produced by standard Histogram to produce "double-sided" and rotated rectangles: ceF := Dynamic@(...

Converting a rotation matrix to a quaternion

I found a very good link about quaternions in Mathematica , but I don't know how to create a quaternion from a rotation matrix. Can anyone help me, please? Update I need this: A rotation may be converted back to a quaternion through the use of the following algorithm. The process is performed in the following stages, which are as follows: Calculate the trace of the matrix T from the equation: T = 4 - 4x^2 - 4y^2 - 4z^2 = 4( 1 - x^2 - y^2 - z^2 ) = mat[0] + mat[5] + mat[10] + 1 If the trace of the matrix is greater than zero, then perform an "instant" calculation. S = 0.5 / sqrt(T) W = 0.25 / S X = ( mat[9] - mat[6] ) * S Y = ( mat[2] - mat[8] ) * S Z = ( mat[4] - mat[1] ) * S If the trace of the matrix is less than or equal to zero then identify which major diagonal element has the greatest value. Depending on this value, calculate the following: Column 0: S = sqrt( 1.0 + mr[0] - mr[5] - mr[10] ) * 2; Qx = 0.5 / S; Qy = (mr[1] + mr[4...

mathematical optimization - Formulating a tailor-made Maximum Flow problem in a directed graph

Let a digraph, G , be given, where t[i,j] and a[j,i] , respectively, denote transfer capacity of i allocated for transferring its information to j and absorption capacity of j allocated for absorbing information coming from i . The term, x[i] , defines the information holding capacity of vertex i . If the amount of information inflowing to vertex i is larger than its capacity, then vertex i will refuse the extra information. The following code generates an example digraph G with n=6 : Clear[trs, abs, info, edgeCapMat, system1, reducedSystem1, sa, wG1]; SeedRandom[14]; n = 6; d = 0.3; G1 = RandomGraph[{Round[n], Round[n*(n - 1)*d]}, DirectedEdges -> True]; trs = Table[ Table[t[i, j], {j, 1, n}], {i, 1, n}]; abs = Table[ Table[a[i, j], {j, 1, n}], {i, 1, n}] // Transpose; info = Table[x[i], {i, 1, n}]; infoStocks[stock_] := DiagonalMatrix[stock]; edgeCapMat[trsCap_, absCap_] := (trsCap*absCap) - DiagonalMatrix[Diagonal[trsCap*absCap]]; (* @JMissomewhatokay's contribu...