# Tag Info

5

You can use the new (in V10) ImplicitRegion function as follows: reg = ImplicitRegion[0 <= x <= 1, {x}]; Then: ArgMax[f1[x], x ∈ reg]

2

You have a good answer already, but I'll mention the following since it may be useful in the future. Many built-in functions are written in MATLAB and can be viewed, in this case edit nextpow2.m brings up the source for this function, which can be used as a starting point to implement in Mathematica.

9

How about this? nextpow2[a_] := Ceiling@Log[2, Abs@a]; The same thing in a different style: f1 = Ceiling @* Log2 @* Abs; (* v10 syntax *) Or: f2 = ⌈Log2 @ Abs @ #⌉ &; A plot: Plot[f2[x], {x, -10, 10}, Filling -> 0]

7

As Kuba comments Level follows the standard expression traversal order: Level traverses expressions in depth-first order, so that the subexpressions in the final list are ordered lexicographically by their indices. This is actually a depth-first postorder traversal. It is the normal order in which expressions are evaluated in Mathematica: echo[x_] := ...

2

rcollyer pointed out in a comment that the the new GroupBy may be substituted for GatherBy in Szabolcs's original to produce the desired function: cleanPosIdx[x_] := GroupBy[Range @ Length @ x, x[[#]] &] I shall be using this code until PositionIndex receives an enhancement.

2

Compile: TensorRank: { {{2,3},{1,2.},{1,1.}}, {{2,3.},{1,2},{1,1}}, {{2,3},{1,2},{1,1}} } // TensorRank 3 Therefore: cfn = Compile[{{p, _Real, 3}}, Plus @@@ p]; {{{2, 3}, {1, 2.}, {1, 1.}}, {{2, 3.}, {1, 2}, {1, 1}}, {{2, 3}, {1, 2}, {1, 1}}} // cfn {{4., 6.}, {4., 6.}, {4., 6.}} If you are using an older version of Mathematica use ...

2

I get a better fit with an asymptotic complexity between n^4 and n^5. I think Det is doing a lot of simplification of symbolic expressions, which may account for some of the increased complexity. nMax = 35; entry[] := RandomInteger[{-9, 9}] + RandomInteger[{-9, 9}]*t findTime[n_] := Block[{m, time, det}, m = Table[entry[], {i, 1, n}, {j, 1, n}]; {time, ...

4

Mathematica does not automatically calculate the quantile (or InverseCDF) for arbitrary distributions. You need to do it. xd = ExponentialDistribution[1]; (* use exact argument *) yd = ExponentialDistribution[5]; (* use exact argument *) td = TransformedDistribution[ x/(x + y), {x \[Distributed] xd, y \[Distributed] yd}]; quantile[q_] = z /. ...

10

I closed this question because rm -rf convinced me that what this answer was intended to do is ultimately impossible: that there is simply no way to give an approximate one-to-one mapping of functions between Octave/Matlab and Mathematica; apart from a few limited cases any recommendations are going to be localized and opinionated rather than truly ...

1

You have two issues - firstly data includes x values and you don't want to convolve those. So use data[[All, 2]] in the convolution. Secondly you need to allow the kernel to overhang the data or you'll just get the single value of the convolution with the kernel aligned to the data. The overhang is determined by the third argument of ListConvolve. See the ...

0

Improving a bit on @Sjoerd C. de Vries comment, you use SlotSequence (##) to do the following: c = {x1, x2}; T = Array[t[##] @@ c &, {2, 2}] { {t[1, 1][x1, x2], t[1, 2][x1, x2]}, {t[2, 1][x1, x2], t[2, 2][x1, x2]} } Taking partial derivatives w.r.t. to one of the coordinates (just to name an example) then works as expected: D[T, x1]

2

I shall not attempt to replicate the exact function of your code but rather to address the problem posed in text of your Question. As a starting point I suggest you build a Dispatch table of the replacements you wish to make and then apply it with Replace. First some sample data: SeedRandom[0] m = RandomInteger[66, {1024, 1024}]; keep = Array[Prime, 18]; ...

3

I guess I'll answer my question. As Leonid Shifrin alluded to in the comment, AllTrue is actually a more general function than VectorQ and this has various consequences: (1) VectorQ is overloaded to work efficiently with packed arrays which is evident from my benchmark above. (2) If we append a non-integer to the example in the question, we no longer have a ...

2

SelectComponents is pretty fast but it labels the background with 0, not 100. You might be able to work with that. SelectComponents[mat, "Label", MemberQ[keep, #] &] but this is a bit faster: sel = Compile[{{label, _Integer}, {keep, _Integer, 1}}, If[MemberQ[keep, label], label, 0], (* or 100 if necessary *) RuntimeAttributes -> {Listable}, ...

3

In order to apply a function to every element we can use Map with the level specification: Map[If[MemberQ[keep, #], #, 100] &, matrix, {2}] Another option using the Listable attribute: Function[{x}, If[MemberQ[keep, x], x, 100], Listable]@matrix; This turned out to be a lot slower though. I ran these on Michael E2's test case and the Listable ...

11

This function will be rewritten in C for 10.0.2 and should come down to average-case complexity of $O(n)$ from its current $O(n \log(n))$. Note that the version most users will be bothered to write (and the way we advertized this before in the docpage for DeleteDuplicates) is $O(n^2)$, so most users are probably already winning. In the meantime, my advice ...

0

Plus is protected. but you can use unprotect. Unprotect[Plus]; F_[1, j___] + F_[2, j___] + F_[3, j___] := Defer@Sum[F[i, j], {i, 1, 3}] Protect[Plus];

23

Summary We can look at the code of DeleteDuplicatesBy and it turns out it uses GroupBy. The test cases proposed by Mr.Wizard are all handled by some part of the code of DeleteDuplicatesBy. Other parts of this code also seem to have some issues. Most of the members of the *By family of functions seem to have side effects. How DeleteDuplicatesBy works It ...

16

Attempting to analyze the performance of this function in the manner that Taliesin Beynon did for PositionIndex I shall use the same tools. The old method that will be compared in all cases below: myDeDupeBy[x_, f_] := GatherBy[x, f][[All, 1]] Speed A BenchmarkPlot of DeleteDuplicatesBy versus myDeDupeBy: Needs["GeneralUtilities"] BenchmarkPlot[ ...

1

SetDelayed Just inserted some SetDelayed assignments. Thought the 3rd one (xsi) gave reason for messages. It works fine now. Clear@"*" N1[λ_, n_] := Sqrt[(2*λ - 2 n - 1)*Gamma[n + 1]/Gamma[2*λ - n]] b[λ_, n_, j_] := (-1)^j*(1/j!)* Gamma[2*λ - n]/(Gamma[2*λ - 2 n + j]* Gamma[n - j + 1]) ξ[λ_, y_] := 2*λ*Exp[-y] f[λ_, m_, n_, y_, k_] := ...

1

Question How do I prevent Part[] from trying to decompose symbolic expressions when it is evaluated? Mathematica 10 implements something like your listPart (with additional functionality): Indexed: Indexed can be used to indicate components of symbolic vectors, matrices, tensors, etc. When expr is a list, Indexed[expr,i] gives ...

0

After some contemplation (and some errating comments) I realized that exactly on the real axis above z=1 the function PolyLog(k,z) is not well defined but a choice must be made from which bank of the branch cut we are approaching the real axis (hence my "contemplation" led to a well known result). Mathematica has made that choice which is, however, hidden in ...

2

This might be what you're after (although some more details would indeed help): hessian[im_] := Map[ { {gD[#, 2, 0, 2], gD[#, 1, 1, 2]}, {gD[#, 1, 1, 2], gD[#, 0, 2, 2]} } &, im, {2} ]; This is almost Karsten's suggestion, the difference being the third argument to Map, {2}. It tells Map to only map on elements at level 2 of the input ...

2

I was somewhat perplexed by your use of Module here, and I don't think you every explicitly stated the reason you are using it, but I am going to assume that you want to prevent e.g. f[-6] from having a global value after your operation is performed. For that you want Block instead of Module. You will also need to Evaluate lengthRow or you will reassign ...

1

I'd go for Count: Count[row, 2] 3 And in case you want to count all elements of your row, you can also use Tally: Tally[row] {{-1, 5}, {1, 5}, {2, 3}, {3, 1}, {-2, 2}, {-3, 2}, {-4, 1}, {-5, 1}} EDIT Given the OP's updated goal, this should suffice: row /. Rule @@@ Tally[row] {5, 5, 3, 1, 5, 5, 3, 5, 5, 5, 2, 2, 5, 5, 2, 2, 1, 1, 5, 3} ...

27

First let me note that I didn't write PositionIndex, so I can't speak to its internals without doing a bit of digging (which at the moment I do not have time to do). I agree performance could be improved in the case where there are many collisions. Let's quantify how bad the situation is, especially since complexity was mentioned! We'll use the ...

16

I see no mention of the new-in-10 PositionIndex in the other answers, which takes a list (or association) of values and returns a 'reverse lookup' that maps from values in the list to the positions where they occur: In[1]:= index = PositionIndex[{a, b, c, a, c, a}] Out[1]= <|a -> {1, 4, 6}, b -> {2}, c -> {3, 5}|> It doesn't take a level ...

8

I'm the one inside the company who suggested RightComposition (and pushed for syntax for Composition and RightComposition). I'm sympathetic to your need, and have wanted the same thing once or twice myself. Given that not much /* and @* code has been written yet, I think it is certainly possible we could have /* parse to LeftComposition. I'm not sure what ...

6

Using this site as my rubber duck and attempting to answer my own questions: (1) Reason for existing behavior One may want to be able to do this: heldRow = HoldForm @* Row @* List; (* version 10 syntax *) x = 7; Block[{x}, heldRow[x + x + x, x^2*x^3] ] 3 xx^5 (* proposed behavior would yield: x+x+xx^2 x^3 *) My counterargument: this ...

5

One difference I just run into is Dispatch. To get the original rules, use First@Dispatch[•••] in v9, but Normal@Dispatch[•••] in v10.

8

Multiple versions of Mathematica can co-exist on a computer without problems. The best approach is to have both version 10 and version 9 installed simultaneously until you are confident that all your critical code work with 10. When using multiple versions it is useful to go to Preferences -> System and check "Create and maintain version specific front end ...

1

Each new release of Mathematica, from V6 on at least, has come with a compatibility checker that intervenes each time you open a notebook created in an earlier version and warns you of code that it thinks might break because of revisions to functions that were part of previous releases. I don't have V10 yet, but I would expect it to a compatibility checker, ...

1

Answering my own question from a while ago. Turns out the easiest method is using MMA’s built-in Computer Math library << ComputerArithmetic` (*Set Math Parameters*) SetArithmetic[6, 10, ExponentRange -> {-20, 20}]; fpConvert[x_, integerbits_, fractionbits_] := ComputerNumber[IntegerPart[x] + Round[FractionalPart[x], 2^-fractionbits]]; Let’s ...

8

Some functions have new return types in MM10. For instance, I'm running into trouble with date functions (like DatePlus) since they return DateObjects in MM10 but returned date lists in MM9. Other functions (like DateDifference) now return Quantity objects instead of a number.

2

iter = Reap[FindRoot[Sin@x == Cos[x], {x, 0}, EvaluationMonitor :> Sow[x]]] {{x -> 0.785398}, {{0., 1., 0.782042, 0.785398, 0.785398}}} Length@Last@Last@iter - 1 4

2

Options[FindRoot] (* {AccuracyGoal -> Automatic, Compiled -> Automatic, DampingFactor -> 1, Evaluated -> True, EvaluationMonitor -> None, Jacobian -> Automatic, MaxIterations -> 100, Method -> Automatic, PrecisionGoal -> Automatic, StepMonitor -> None, WorkingPrecision -> MachinePrecision} *) ?? EvaluationMonitor (* ...

0

\$Version "9.0 for Mac OS X x86 (64-bit) (January 24, 2013)" Clear[delta]; delta := NDSolve[{ y''[n] + y'[n] - y[n] == 0, y[-3] == 1., y'[-3] == 1.}, y, {n, -3, 0}]; Do[ Print[ Timing[ Table[ (y /. delta[[1]])[-2], {1000}] // Union]], {i, 10}] {1.743167,{2.13832}} {2.285117,{2.13832}} {2.801171,{2.13832}} ...

0

The problem lies in the incorrect use of the E notation for large and small numbers, such as 6.47368e-07. You should indicate powers of 10 explicitly: 6.47368*10^-7 If you want to clean up your notation, you should note that (i) spaces between numbers are always interpreted as products, (ii) you can get nice-looking multiplication signs by typing ...

1

I've actually managed to answer it myself - will answer here if it's any good to others; Ebound[r_] = Piecewise[{{Eb1[rn, 14400] /. x, r < rn}, {Eb1[r, 14400] /. x, r > 0}}]; Plot[Ebound[r], {r, 0, ro}, PlotRange -> Automatic] this gives the expected behaviour;

2

You can define f to operate on f however you would like: ClearAll[f] f@f := f@f@# &; f[x_] := x /. a -> I a {f[a], f@f[a], (f@f)[a]} {I a, -a, -a} However if you expect this to extend to e.g. (f@f@f)[a] you may want something like: ClearAll[f] f[f] = Superscript[f, 2]; f[Superscript[f, n_]] := Superscript[f, n + 1] Superscript[f, n_][x_] := ...

0

Since you are specifically interested in pattern matching rather than functional equivalents such as the one presented by eldo here is an additional answer. Szabolcs already gave my preferred solution, which is to use Alternatives, though he did not recommend it. Nevertheless I do. As complete code for reference: foo[rules : _Rule | {__Rule}] := ...

1

I don't think you can "follow" the steps taken, but you surely can see how the resulting matrix is formed by "augmenting" your matrix with the identity. Following the last example on the docs about RowReduce[]: m = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; a = Transpose[Join[Transpose[m], IdentityMatrix[Length[m]]]]; MatrixForm[r = ...

3

When you use the syntax f[x_]:= ... in Mathematica, you are not defining a function f. You are defining a pattern-replacement rule. The documentation and the users tend to be vague or misleading or just incorrect about this point. Of course you can define "function" as something quite to your liking and ignore the protestations of mathematicians, ...

1

The OP asks in a comment: One more question. Clear[f, g];f = g;f[x_] = x^4, I can understand the result of ?g. However, why {g,h,j}[[1]]=6 causes error? When using =(Set), MMA first evaluate the first part f and {g,h,j}[[1]] to g and g right?(i.e. always evaluating lhs before assignment) Why is f[x_] = x^4 ok, but not {g,h,j}[[1]]=6? The OP indicates ...

15

I'm guessing you're coming from a programming language where every expression must evaluate to a value, and if it didn't evaluate to something (like 5[Cos+Sin]), it's a syntax error. To me, Mathematica started to make a lot more sense, once I stopped thinking about functions and values, and started to think of every expression as evaluating to an "expression ...

2

Reduce[x^2+y^2==(2 x^2+2 y^2-x)^2,{y},{x},Reals] -((3 Sqrt[3])/8) <= y <= (3 Sqrt[3])/8

Top 50 recent answers are included