Hot answers tagged

34

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[...


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 ...


20

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, ...


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 ...


16

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] (...


14

You need to use === (or SameQ) instead of == (or Equal) to test the condition. This is because === always returns True or False, whereas == can remain unevaluated. For example: a === b (* False *) a == b (* a == b *) The fact that == remains unevaluated is why it is useful in Solve, Reduce and related functions, where you can write an expression such as ...


13

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]...


11

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}] (* ...


11

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[...


11

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 ...


10

At issue is what is being returned by Equals (==). Since both what and whoops do not have values associated with them (OwnValues, in specific), what == whoops returns unevaluated. So, If cannot process it as either True or False, so it remains unevaluated. A way to correct this is to provide a third argument to If, the neither option: Apply[(If[#2 == what, "...


10

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, {...


10

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 ...


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 ...


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 ...


8

You mean something like this? SetDirectory[NotebookDirectory[]]; m = Import["f.txt", "Table"]; getColor[m_List, i_Integer] := Module[{lim1 = 0.0001, f = m[[i, 6]], s = m[[i, 7]]}, Which[ f > lim1 && s == 0, Orange, f <= lim1 && s == 0, Red, f > lim1 && (s == 1 || s == 2), Green, f <= lim1 && (s =...


8

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] < ...


8

Since you're not using Which for more complex constructs or using a "default value", I suggest discarding the Which construct and instead adopting a far simpler approach to defining your Capex function: capex[rom_, CCSP_, wash_, mining_] := -100 ( CCSP > 500 ) + -5 ( rom >= 200 && rom < 300 ) + -10 ( ...


8

Please see J.M.'s answer (in comments) using DirichletConvolve. I would vote for this as an answer. I present my answer: l[c_, n_] :=Module[{r = Range[c]}, Total[(1/r) Total /@MapThread[MoebiusMu@#1 n^(#2/#1) & ,{Divisors /@ r, r}]]] I will happily delete and vote for JM answer.


7

Yes, it is possible. However, it requires the use of the undocumented System`Private`$Localized, which was (as far as I know) first discovered by @Rojo. This symbol is most likely an internal implementation detail of the evaluator and, being located in a context that is obviously not meant for manipulation by the user, should be approached with caution. It ...


7

This is more than you've asked but tell me if this works for you. I've added artificial border with 2s around the world :) init[] := (dim = {10, 10}; world = ArrayPad[RandomInteger[{1, 10}, dim], {1, 1}, 2]; known = ArrayPad[ConstantArray[0, dim], {1, 1}, 2]; p = {2, 2}; (known[[##]] = world[[##]]) & @@ p;) init[] MatrixForm /@ {world, known} ...


7

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 ...


7

I chose the WienerProcess as the underlying random process, as this will simulate a Brownian motion. Until Boundary Hit Module[{rd = Transpose @ RandomFunction[WienerProcess[], {0, 1000, .01}, 2]["States"], length}, length = LengthWhile[rd, # ∈ Rectangle[{-2, -2}, {+2, +2}] &]; ListPlot[rd[[;; length]], Joined -> True, Mesh -> All, PlotRange -&...


7

NIntegrate[f[t], {t, -1, x}] integrates the same thing over and over again, when a point is needed by Plot. Integrate what you need one time only: f[x_] = Which[-1 <= x <= 0, x, 0 <= x, x^2, True, 0]; ϕ[x_] = NDSolve[{Derivative[1][g][t] == f[t], g[-1] == 0}, g, {t, -1.5, 1}][[1, 1, 2]][x]; Plot[ϕ[x], {x, -1.5, 1}]


7

How to define such functions If you want to define a function that has optional arguments and also takes (zero or more) options, a good way to do it is to make patterns specific and ensure that no unexpected matches will happen. I like to do something like this: f[x : (_?NumericQ) : 0.1, opt : OptionsPattern[]] := ... We want to make sure that: opt ...


6

You can use GenerateConditions->False to eliminate conditions (assuming they do not affect your planned use): S[x_, l_] := (C[1] + Integrate[ E^(2 Sum[t^i/i, {i, 1, l - 1}]) (1 - t)^2* Sum[(l - i*2) t^i, {i, 1, l - 1}]/((t - 1) t^l), {t, 1, x}, GenerateConditions -> False]) x^(l - 1)* E^(-2 Sum[x^i/i, {i, 1, l - 1}])/(1 - ...


6

This answer intends to answer both parts of the question. Originally it answered only the first part. Below is the original answer. Scroll down for the second part. I interchanged the third and second argument of ForAll and gave the function IsSuppFun attribute HoldAll, and it worked! So I wrote SetAttributes[IsSuppFun, HoldAll] IsSuppFun[f_[t_]] := ...


6

Your posted code does not work because some of the code you want to evaluate is given as an argument to Condition which holds its arguments, you could make it work by changing this f[x_] := Block[{ans, success}, ans = If[x >= 0, success = 1; Sqrt[x], success = 0]; ans /; (success == 1) ] Notice that the first line of code is process outside ...


6

Something like Pick @@ Transpose@largetable~Join~{0} might do it. Unless 0 should be the Real number 0. If you have both, then try Pick @@ Transpose@largetable~Join~{0 | 0.} Edit: The above is the same as Apply[Pick, Join[Transpose[largetable], {0 | 0.}]] and has the same effect as With[{columns = Transpose[largetable]}, Pick[columns[[1]], columns[[...


6

One can use x-Floor[x] instead of FractionalPart[x] for positive x FullSimplify[Cos[2 Pi ((i + j + k)/2 - Floor[(i + j + k)/2])], Assumptions -> (i | j | k) ∈ Integers] (-1)^(i + j + k)



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