Tag Info

Hot answers tagged

12

Q2: This answer has been sitting in my trunk of files for a year and a half now. I was hoping to improve it and use it to solve the original problem but never got around to it, at the moment it solves images/photos with noisy data. Might as well post it before I forget how it even works. So I wanted to solve this problem with a Minimum Spanning Tree ...


10

I think this is a good case for a simple code generation. Here is one way to generate multiple Do in a macro-like fashion: ClearAll[multiDo]; SyntaxInformation[multiDo] = {"LocalVariables" -> {"Table", {2, Infinity}}}; SetAttributes[multiDo, HoldAll]; multiDo[code_, rest___, iter_] := multiDo[Do[code, iter], rest]; multiDo[code_] := code; Basically, ...


10

As Mr.Wizard already noted, it's not clear whether "operator form" occurs in the documentation of every command that has an operator form (or conversely, e.g., NDSolve*, which references the operator form of Inactive). docdir = FileNameJoin[{$InstallationDirectory, "Documentation", "English", "System", "ReferencePages", "Symbols"}]; docs = ...


7

My own documentation-based approach using usage messages: file = FileNameJoin[{$InstallationDirectory, "SystemFiles", "Kernel", "TextResources", $Language, "Usage.m"}]; usage = Import[file, "HeldExpressions"]; usage // Cases[ HoldPattern[ _[_[sym_Symbol, "usage"] = _String?(StringContainsQ["operator form"])] ] :> sym ] ...


7

Never use pattern matching unless you absolutely have to. Using Cases instead of Select can make a huge difference. Vectorize operations. Use Range instead of Table if you can. Test several things at once. And[test1, test2, test3] will abort when it can for maximum efficiency ("short circuit evaluation"). Taking this into consideration your code looks ...


6

As shown by @LLIAMnYP Clear[f] f[0] = 10.; Do[f[i] = f[i - 1] - Log[f[i - 1]], {i, 10}] The calculated function values are f /@ Range[0, 10] {10., 7.69741, 5.65653, 3.92372, 2.55668, 1.61797, 1.1368, 1.00858, 1.00004, 1., 1.} This sequence can also be generated with NestList NestList[# - Log[#] &, 10., 10] {10., 7.69741, 5.65653, 3.92372, ...


5

This is an interesting, if (necessarily) ill-posed question. My approach is to couch it in more general terms and attempt to clarify what is possible, natural and generalizable by exploring the meaning of "clean", "efficient" and "non-contrived". Some implications for language design are also discussed. max = 5000; val := 2 (2 n^2 + (y - 2) (z - 2) + x (y ...


5

I don't know any direct way to do what you wantand I agree that it would be an improvement if in a future release GeoDistance will supports a GeoPath as argument. But even now it's not so difficult to compute the distance along a path with with a not-so-"brute" way and this definition: geoPathDistance[locations:{__GeoPosition}] := Total[GeoDistance @@@ ...


5

It can be done with Switch, but that would be an awkward application of Switch. Clear[a, b, c, d]; With[{x = 42}, Switch[x, _?(# == 10 &), a = 3; b = 7; "==10", _?(# > 10 &), a = 5; c = 6; ">10", _, a = 7; d = 12; b = 1; "Otherwise"]] ">10" {a, b, c, d} {5, b, 6, d} However, Which is a better choice Clear[a, b, ...


4

As I mentioned in my comment, of course Mathematica has a built-in function to calculate the GCD, called GCD (docs). My understanding, however, is that you are using the GCD as an example to learn how to apply a function recursively for a number of times that is not decided a priori, but that depends on the inputs and the path of the calculation. The ...


4

You have defined the elements of group and could approach as follows: r[a_] = RotationMatrix[a Degree]; rot = {r90, r180, r270} = r /@ Range[90, 270, 90] ref = {rh, rv, d1, d2} = ReflectionMatrix[#] & /@ {{1, 0}, {0, 1}, {1, 1}, {-1, 1}}; tab = {IdentityMatrix[2]}~Join~rot~Join~ref; rules = {IdentityMatrix[2] -> "\!\(\*SubscriptBox[\(R\), ...


4

Preamble There are some important differences (or, more precisely, features of Function which can't be reproduced with symbols and rules), that have not been reflected in answers here, but that I think deserve a separate answer. These are related to some more advanced uses, involving evaluation control, closures, and garbage collection. Emulating Hold ...


4

This is a form definition: ff = FormFunction[FormObject[<|"x" -> "Number"|>], #x^2 &] Now watch the [] after the ff, this launches the form and waits for input and shows a submit button ff[] If you want put a value in the form without showing a submit button: ff["x" -> 9] Does this answer your question?


4

Here is the simple method I use. I create a button (with label "[[?]]") that finds the position of the current selection in the last output. You can add the button to a custom utilities palette for easy access. Button["\[LeftDoubleBracket]?\[RightDoubleBracket]", Print@Position[%, ToExpression@CurrentValue@"SelectionData"]] Here's how to use it to grab ...


4

First problem, subscripts start with 1 in Mathematica, not 0 like in many other languages. One alternative z = List[82, 57, 40, 22, 41, 8]; n = List[0.1973, 0.002, 0.1068, 0.0930, 0.002, 0.5989]; Zm2[Z_, nk_] := Sum[nk[[i]]*Z[[i]]^2, {i, 1, Length[Z]}]; Zm2[z, n] which gives 1590.73 Or perhaps just using Total[n*z^2] which gives the same result, but ...


3

In Mathematica every inter-Kernel communication comes with significant overhead. Your simple Do loop with a shared Sow on every value is about the worst possible situation. Instead (for performance) you want to gather results within each Kernel and only pass them back to the master in a single call. (Or at least a limited number of calls.) Using linked ...


3

How to use both initialized and uninitialized variables A variable in Mathematica can play two different roles. As an initialized variable, the variable's value will replace its name when an expression is evaluated. By contrast, upon evaluation, the name of an uninitialized variable will be propagated throughout every expression in which it takes part. For ...


3

Given that you just want to relabel the square each time, it's probably easiest just to view this as a set of permutations. Imagine numbering the corners of the square clockwise from the upper left. When we do an operation on the square, we could then write down a list of the corner that's in each position. For example, {1,2,3,4} would correspond to the ...


3

Not withstanding the keys with spaces issue. Dataset doesn't automatically reform itself to drop unneeded columns. You need this : segmentMap[Select[#State == 1 &]] // Normal // Dataset There's probably also a "pure" dataset version without dropping into Normal although I can't think of one right now that doesn't need you to specify the key names. ...


3

This specific slowdown is solved in Mathematica 10.1. Probably it was not just DownValues but something else. Anyway. Other slowdown's are still there, unfortunately, but they are harder to pin down. So at least this artificial example is solved.


3

a 'loopless' one liner.. This takes ~5 minutes, way slower than the original, but considerably faster that Ronald's.. max = 5000; Clear[val, x, y, z, n] val[x_, y_, z_, n_] := 2 (2 n^2 + (y - 2) (z - 2) + x (y + z - 2) + 2 n (x + y + z - 3)); a = Normal@ SparseArray[Rule @@@ #, max] &@(val[x, y, z, n] /. FindInstance[ val[x, ...


2

In version 10 even a single Rule will produce a Dispatch object: Dispatch[ a -> 1 ] // InputForm Dispatch[{a -> 1}] Dispatch[ a -> 1 ] // AtomQ True Association is also a hash structure and provides a comparably fast alternative to Dispatch, which an interface for adding, deleting and updating rules. In many cases Associations may be ...


2

Method 1 gcdList[x_, y_] := FixedPointList[ # /. {a_, b_} /; b != 0 :> {b, Mod[a, b]} &, {x, y}] gcdList[25,45] {{25, 45}, {45, 25}, {25, 20}, {20, 5}, {5, 0}, {5, 0}} Another solution gcd[a_, b_] := Module[{x, y}, {x, y} = {a, b}; While[y != 0, {x, y} = {y, Mod[x, y]}; ]; x ] gcd[15,10] 5 Method 2 gcdList2[a_, b_] ...


2

Fix your error The initial value of index i should be 1, not 0. If the value is 0, it means extracting the Head of the nk and Z, namely, List . In addition, i < Length[Z] should be i <= Length[Z], Zm2[Z_, nk_] := Module[{zm2 = 0, i}, For[i = 1, i <= Length[Z], i++, zm2 += nk[[i]]*Z[[i]]*Z[[i]];]; Return[zm2]; ] Zm2[z, n] 1590.73 ...


1

I think the function you are looking for is CoefficientArrays; here is its documentation. Your system is quite complex so I will let you deal with its intricacies, but here is a demonstration on a toy example. Let's define a set of linear equations in $x$, $y$, and $z$: eqns = {2 x - y + 4 z == 12, 3 x + 2 y + z == 10, -y + z == 1}; The solutions of ...


1

I cannot comment, so that is a suggestion: a = Zm2[z, n][[1]] Thus a is a variable you are looking for. You may aviod the need for this just starting loop from i=1, not i=0. And, depending on your needs, set i < Length[Z] + 1. So, your result if you loop through 5 elements will be 1552.4, but with all 6 elements you will get 1590.73. Note, that ...


1

Another way: Module[{dist = 0}, Fold[ (dist += GeoDistance[##]; #2) &, locs[[tour]]]; dist] (* Quantity[6898.75, "Miles"] *) If locs is the other path to compare with: Module[{dist = 0}, Fold[ (dist += GeoDistance[##]; #2) &, locs]; dist] (* Quantity[30490.5, "Miles"] *)



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