Tag Info

48

To answer your question: I don't think it's a bad or good idea to use If. It depends on how you do it. To demonstrate I'll use If combined very powerfully with Mathematica 10's ability to tell if a point is inside a specified region or not. step[position_, region_] := Module[{randomStep}, randomStep = RandomChoice[{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}]; If[...

25

Ramblings Arguments of the left-hand-side head are evaluated in the course of function definition, therefore you can use a utility function that constructs the patterns that you want. For example: SetAttributes[nq, HoldFirst] Quiet[ nq[s_Symbol] := s_?NumericQ ] Now: ClearAll[f] f[nq @ a, nq @ b, nq @ c] := a + b + c Definition[f] f[a_?NumericQ, b_?...

23

A more general way, which can be used for other functions like Solve, is to use Normal. Integrate[1/x^s, {x, 1, Infinity}] (* ConditionalExpression[1/(-1 + s), Re[s] > 1] *) Normal[%, ConditionalExpression] (* 1/(-1 + s) *) Edit It looks like as of version 10, one can just use the one argument Normal: Integrate[1/x^s, {x, 1, Infinity}] (* ...

23

I suggest using Mod - a natural thing for looped boundary conditions on a torus. Finite torus surface area is your bounded region. 2D random walk generally is simple: walk = Accumulate[RandomReal[{-.1, .1}, {100, 2}]]; Graphics[Line[walk], Frame -> True] Confinement to square region {{0,1},{0,1}} would be simple in principle with Mod[walk,1] (periodic ...

21

A story of incremental improvement Let's look at the OP's original expression again, for reference: $$\sum_{m=1}^{c}\frac{1}{m}\sum_{d \mid m}\mu(d)n^{m/d}$$ Most people here are familiar with Sum[], and would not have much trouble translating the outer summation into Mathematica syntax. The inner part, $$\sum_{d \mid m}\mu(d)n^{m/d}$$ is not terribly ...

17

When using Set rather than SetDelayed you will need to hang the Condition on the left-hand-side: ClearAll[f] f[x_] /; x > 0 = Sqrt[x] f[2] f[-2] Sqrt[x] Sqrt[2] f[-2] There are other reasons to prefer this placement; see: Placement of Condition /; expressions However be aware that the use of Set results in "pre-evaluation" of the RHS which often ...

17

The main difference is their intended use. Which is a "programming function". It is meant for flow control. It is an equivalent of if ... elseif ... elseif ... end in procedural languages. Piecewise is a "mathematical function". It is meant for a symbolic representation of piecewise functions. This distinction is not perfect—in Mathematica it never is—...

16

Select[ IntegerPartitions[24, {8}, Range[5]], #.# == 86 & ] {{5, 5, 4, 2, 2, 2, 2, 2}, {5, 5, 3, 3, 3, 2, 2, 1}, {5, 4, 4, 4, 2, 2, 2, 1}, {5, 4, 4, 3, 3, 3, 1, 1}, {4, 4, 4, 4, 4, 2, 1, 1}} Slightly more general approach (in case where IntegerPartitions is not what we need): ClearAll[ar, a]; ar = Array[a, 8] ar /. Solve[Flatten@{ Tr[ar] == ...

15

f[...] := Module[{...}, ... /; condition] is a very special syntax (documented in the Details section of Module). It only works if the right-hand side of the := operator contains a Module. In your example, it contains a Flatten, the Module being buried at a lower level. What is important to remember is that a /; condition inside of a Module/Block/With must ...

15

You can use DeleteDuplicates with Greater as the second argument: DeleteDuplicates[lst, Greater] {1, 65, 155} Alternatively, you can use FoldList to apply Max recursively and take Union of the resulting list: lst = {1, 65, 40, 155, 120, 122}; Union @ FoldList[Max] @ lst {1, 65, 155} You can also use DeleteDuplicates in place of Union ...

14

I think it's easier just to define this straight up, rather than compute something procedurally. f[1, 0] = 77; f[0, 1] = 66; f[_, _] = 0; Mathematica is fundamentally an expression rewriting system, so telling it how to rewrite expressions directly like this is usually clearer, faster, and easier to debug.

13

Here's my implement of a random walk within a circle using If and FoldList. Please see @Pickett's answer for more thorough implementation for arbitrary regions. Code updated to flesh out behavior near edge of region (if a step becomes out of bound, the current position will randomly look for the other step types that would stay in the region). I also added ...

13

It seems this question is now purely about style and will probably be closed. However I think you may be looking for this: If[x < 1, ( y = 2 x; z = 2 y ), ( y = x/2; z = y/2 ) ] Though I would prefer (hat tip to WReach's comma placement): If[x < 1, y = 2 x; z = 2 y , y = x/2; z = y/2 ] If your code is very long I suggest you ...

13

A drawback of the Which command is that it evaluates x repeatedly until one of the conditions of Which is satisfied. This is time consuming when x is a complicated expression or/and when the set of conditions is large. This is not true in Compile as x will always be a number or an array. Multiple uses of x won't slow anything down. It isn't even true ...

13

Using Ramp and vectorized operations: y = -.02 Range[0, 4 10^5]; Total @ Sqrt[Ramp[1 - 2 Exp[y]]] //AbsoluteTiming {0.018728, 399935.}

12

tbl = RandomInteger[{0, 3}, {10, 2}] (* {{0, 3}, {0, 0}, {1, 3}, {2, 0}, {2, 0}, {0, 0}, {1, 1}, {2, 2}, {1, 0}, {3, 3}}*) You have many alternative methods: Cases[tbl, {x_, 0} :> x] (* or *) Cases[tbl, {_, 0}][[All, 1]] (* or *) DeleteCases[tbl, {_, Except[0]}][[All, 1]] (* or *) Select[tbl, Last[#] == 0 &][[All, 1]] (* or *) Pick[tbl[[...

12

I recently realised that the Replace function essentially solves this problem, but it is not the sort of function you tend to associate with conditional constructs. It also might surprise readers of the code, as it is not a common idiom. This solution is: Replace[expr, {pat1 :> val1, pat2 :> val2, _ :> valD}] e.g. Replace[x, {...

12

Note: This is an incomplete analysis and leads to the wrong conclusion about the cause of the difficulty. Mr.W's answer below correctly identifies the culprit as Condition. The problem you are facing has nothing to do with OptionValue, OptionsPattern, or Condition. It is simply because b__ is under specified and SlotSequence is greedy. Effectively, you ...

12

Perhaps InternalDependsOnQ: h = f[x, g[y]]; InternalDependsOnQ[h, #] & /@ {x, y, g[y], w} {True, True, True, False}

11

I think the easiest way is to use Condition which has the operator form /;. f[x_ /; -1 <= x <= 1, c_] := -(x + c)^2 Then With[{c = -1/4}, Plot[f[x, c], {x, -2, 2}]]

10

Perhaps this? Manipulate[ {names, slide, setter, cases}, Dynamic@Switch[cases, "custom", Control[{{names, True}, {True, False}}], "a", Control[{{slide, 0}, 0, 1}], "b", Control[{{setter, "das"}, {"das", "der", "die"}}]], {{cases, "custom"}, {"custom", "a", "b"}}] The variables seem to get localized properly even though the syntax ...

10

A slightly different approach with Reduce (or Solve) We define: matC = Range[5]; (* the list of the integers from which we build a list *) Let us use a vector to indicate the multiplicities of any integer: matX = Array[ x, 5 ]; (* @Kuba: that's more concise, indeed *) So x[1] will tell us how many times $1$ appears a possible solution. We can then get ...

10

If it is only for displaying purposes you can use Row: PrimeFactorization[x_] := Row[#, "\[Cross]"] & @ (Superscript @@@ FactorInteger[x])

10

Put Flatten inside Module: ClearAll[f] f[list_] := Module[{titi = {r, x, y, u, v, n, l, w, s}}, Flatten@Transpose[{titi, Rest@list}] /; Length[list] > Length[titi]] f[m] {r, 0.3, x, 0.4, y, 0.5, u, 0.6, v, 0.7, n, 0.9, l, 1., w, 1.5, s, 1.6} You could also use Riffle[titi, Rest@list] instead of Flatten[Transpose[{titi, Rest@list}]].

10

As @BobHanlon points out that the probability is zero for a specific value. But probabilities are not (necessarily) 0 in intervals. So we can get a probability statement for an interval and then take the limit as the size of that interval goes to zero. p = Probability[X == 1 \[Conditioned] Abs[X + Z - y] <= δ, {X \[Distributed] BernoulliDistribution[...

9

Since If has attribute HoldRest, the i will not be inserted into the latter parts during the evaluation. Consider this example showing the same effect: Sum[s[i, Hold[i]], {i, 1, 2}] (* s[1, Hold[i]] + s[2, Hold[i]] *) I think the best practices way of getting what you are asking for is to use With to ensure i gets inserted: Sum[With[{i = i}, If[x[i] < ...

9

I suppose it's better to make my comment into an answer, per SE policy. The slowness is due to AppendTo, which has been pointed out by many others before, as well as in the documentation. To get the indices, indices = Pick[Range[Length[w]], UnitStep[w]] will be fast. Reasons for starting variable names with a lower-case letter instead of a capital have ...

9

The ConditionalExpression output by Solve in your case does not really depend on the whole argument of the Log function in your original equation, but only on the following expression: -π < Im[(k t (L - T))/L] ≤ π If it is possible in your case to make assumptions on the values of those parameters, you could then try to Simplify the output of Solve ...

9

You can create random matrices until the eigenvalues do not have a Root form: While[ A = RandomInteger[{-1, 1}, {4, 4}]; !FreeQ[RootReduce @ Eigenvalues[A], _Root] ]; Eigenvalues[A] JordanDecomposition[A][[2]] {-2, I Sqrt[2], -I Sqrt[2], 0} {{-2, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, -I Sqrt[2], 0}, {0, 0, 0, I Sqrt[2]}}

9

For the selection criterion, Select uses a (pure) function, while *Cases uses a pattern. Code below works. DeleteCases[FromDigits /@ Tuples[{2, 3, 5, 7}, 5], _?EvenQ]

Only top voted, non community-wiki answers of a minimum length are eligible