21

You asked for a general explanation instead of just focusing on specific application examples, so here it goes ... The concepts of "pass by reference" and "pass by value" that you may know from languages like C do not apply very well to Mathematica. Do not try to think in this framework. The right question is not "how to pass by ...


20

Okay, let's focus on this snippet: Module[{i, j}, Do[ pe = (volume[[j, i + 1]] pi[[j, i + 1]] + volume[[j, i]] pi[[j, i]])/(volume[[j, i]] + volume[[j, i + 1]]) //. Indeterminate -> "*" // Quiet, {i, 1, 8, 1}, {j, 1, 10, 1}]] Creating some dummy data: volume = RandomReal[{-1, 1}, {10, 9}]; pi = RandomReal[{-1, 1}, {10, 9}]; ...


14

While While[procedure; test] works, it looks very similar to While[test, procedure]. The only difference is ; vs ,. While is not the most commonly used construct, so when used like this there's a high chance of misunderstanding/misreading. If readability/reliability is a concern (for example a collaboratively developed published package), I'd use the ...


10

If you wrap the body of the loop with Catch, then any Throw will act as Continue: r = 0; Do[Catch[ If[EvenQ[i], Throw[Null]]; r += i ], {i, 10}]; r (* Out: 25 *) (Example taken from the documentation for Continue.)


10

Even in MATLAB, this would not be good programming style because successive concatenation is awfully slow. (And for is slow, too.) Better use Table: n = 800; x = RandomReal[{-1, 1}, n]; y = RandomReal[{-1, 1}, n]; Table[ With[{xi = x[[i]], yi = y[[i]]}, Table[ (xi - x[[j]])^2 + (yi - y[[j]])^2 , {j, 1, n}] ], {i, 1, n} ] Better: Table[ ...


10

If you want, you could write some thing like this f[x_] := Module[{k = x}, Do[k = k^2 + 1, {i, 0, x - 1}]; k] A more natural form would be f[x_] := Nest[#^2 + 1 &, x, x]


9

UPDATE: After reposting the below function after modifications from the deleted post to make it work after OP question was changed, I determined a way to utilize ideas from the original deleted post's second, faster function. This is much faster than the second function below for larger arguments (~100 X faster for Np argument of 500) and has less memory ...


9

If you introduce a length bound already, there is absolutely no reason for Append/AppendTo. Such a loop with Append/AppendTo has runtime complexity $O(n^2)$ because Append/AppendTo has to perform a copy of the whole list (which grows longer and longer). So a better practice is to initialize A as a list with the maximal length, to introduce an iteration ...


8

According to the documentation center: Goto first scans any compound expression in which it appears directly, then scans compound expressions that enclose this one. Your Goto - Label construction is part of the List so Mathematica fails to find the label. Taking this under consideration, the following will work: k = 0; Do[{ Label[top]; k = k + 1; ...


8

You need: SetAttributes[myfunc, HoldAll] You then have: myfunc[a_, b_] := {a = 2*a; b = -b;}; vara = 5; varb = 6; SetAttributes[myfunc, HoldAll] myfunc[vara, varb]; {vara, varb} {10, -6} Look for HoldAll, HoldFirst and HoldRest in the documentation and this site. You can do this: myfunc[a_, bIn_] := Block[{b}, {a = 2*a, b = -bIn}]; vara = 5; ...


8

In the Excel object model, the worksheet symbol Cells represents a property, not a method. In Visual Basic and other languages, many properties have a default method called Item. NETLink does not fully implement this notion of a default method: ws@Cells[3, 3]@Value (* 3 *) but: $i = 3; ws@Cells[$i, $i]@Value (* (NETLink`Objects`NETObject$1412516038$...


8

(Subtract @@@ Subsets[Most@x, {2}])^2 + (Subtract @@@Subsets[Most@y, {2}])^2 will produce precisely the output of your OP with appropriate performance. Since your output is a small subset of all-points distances, it should also outperform things like DistanceMatrix. A comparison of OP and this up to 300 length for timing:


7

As I noted in an earlier comment, the ODE to be solved can be rewritten as eq = y'[x] == Log[1 - Exp[-y[x]]] Then, s = First@NDSolve[{y'[x] == Log[1 - Exp[-y[x]]], y[0] == 1}, y, {x, 0, 5}]; Plot[Evaluate[ReIm[y[x] /. s]], {x, 0, 5}, AxesLabel -> {x, y}] where Re[y] is blue, and Im[y] is tan. Because the ODE is singular at y == 0, it is natural to ...


7

Built-in option This sidesteps most of your code, so it might not be what you are looking for, but I believe your goal can be achieved with Mathematica's built-in image processing capability, specifically: MorphologicalComponents! Define a new clustering function clustering1[config_] := Module[{output, csizes, cindices}, output = ...


7

This duplicates the behavior of yours (no effect on zeroes at ends): smoothee=ReplacePart[#, i_ /; i > 1 && i < Length@# && #[[i]] == 0 :> Mean[{#[[i - 1]], #[[i + 1]]}]] &; smoothee[{0, 1, 3, 4, 6, 8, 0, 11, 12, 0, 13, 0}] (* {0, 1, 3, 4, 6, 8, 19/2, 11, 12, 25/2, 13, 0} *) Here's a goofy (...


7

Table[If[Mod[n!, n^(2 n)] == 0, n], {n, 1, 1000}] /. Null -> Sequence[] {1} Cases[Table[If[Mod[n!, n^(2 n)] == 0, n], {n, 1, 1000}], _?NumericQ] {1} Select[Table[If[Mod[n!, n^(2 n)] == 0, n], {n, 1, 1000}], NumericQ[#] &] {1} DeleteCases[Table[If[Mod[n!, n^(2 n)] == 0, n], {n, 1, 1000}], Null] {1}


7

f@@(list1 ~Join~ list2) Or, more generally, use @@ to "open" the structure of List: list1 = {x1, x2, x3}; list2 = {y1, y2, y3}; f @@ (list1~Join~list2) f[x1, x2, x3, y1, y2, y3] For a list of lists: listOflists = {list1, list2} f @@ (Flatten@listOflists) f[x1, x2, x3, y1, y2, y3]


7

The problem with your code is that for some values of c, Abs[z] will never become larger than 2. You need to cap the number of iterations. For this type of iteration, the typical function to use is Nest and related functions. countIter[c_] := Length@NestWhileList[ #^2 + c &, 0.0, Abs[#] <= 2 &, 1, 100 (* limit number of ...


7

Clear["Global`*"] eqns = {n == a^3 + b^3, n == c^3 + d^3, 1 <= n <= 10000, a >= b > 0, a > c >= d > 0}; sol = Solve[eqns, {n, a, b, c, d}, Integers] (* {{n -> 1729, a -> 12, b -> 1, c -> 10, d -> 9}, {n -> 4104, a -> 16, b -> 2, c -> 15, d -> 9}} *) And @@ Flatten[eqns /. sol] (* True *)


7

In addition to the very good suggestions by Fraccalo, the issue here is that Mathematica refuses to overwrite arguments of functions (in general). So you have to introduce a local variable like this: f[n0_] := Module[{n = n0}, While[n < 10, n = n + 1]; n ] There is a way to emulate so-called call-by-reference that you might know from C-like ...


7

Try A={1,2,3,4}; While[Length[A] < 10, A = Append[A, 3.14]] Which gives {1, 2, 3, 4, 3.14, 3.14, 3.14, 3.14, 3.14, 3.14} When you call Length[A] inside the loop using Append[] it only remembers the A that you originally defined, so you need to explicitly 'update' its value. As mentioned in the comment below, AppendTo[A, 3.14] should do the trick: ...


7

PadRight can be used. In a general setting you will need to do PadRight[A, N, element]. As in this case, you can use PadRight[A, 10, 3.14] and assign that list to A itself for appending. This is much faster than While loop approach for larger sets. A = PadRight[A,10,3.14] (*{1, 2, 3, 4, 3.14, 3.14, 3.14, 3.14, 3.14, 3.14}*) Another approach: A = Join[A, ...


7

Update: A faster alternative: foo = Boole @* LessThan[4] @* Length @* Union @* Transpose @* Developer`ToPackedArray @* List; c0 = Outer[foo, mt, mt, 1]; c0 == c True Original answer: mt = Transpose[m]; c1 = Boole @ Outer[Length@Union@Transpose[{##}] < 4 &, mt, mt, 1]; c1 == c True Alternatively, mt = Transpose[m]; c2 = ConstantArray[0, {...


7

To answer your question directly, a loop could be written like this: f = Table[3*k*k, {k, 1, 16}]; Do[ f[[4 i + j]] = 1; , {i, {1, 3}}, {j, 1, 4} ]; f {3, 12, 27, 48, 1, 1, 1, 1, 243, 300, 363, 432, 1, 1, 1, 1} A non-loop alternative is this: f = Table[3*k*k, {k, 1, 16}]; pos = Flatten@Table[Range[4] + 4 n, {n, {1, 3}}]; f[[pos]] = 1; f {3, 12, ...


6

If the goal is to perform a parallel search for the first result that meets some condition, then we can consider using ParallelTry instead of throw/catch: ParallelTry[If[PrimeQ[#], #, $Failed]&, Range[492114, 500000]] (* 492227 *) This evaluates a function for every value in the second argument (in parallel). The first result that is anything other ...


6

Why not write your own and place it in your init.m file? SetAttributes[DoWhile, HoldAll]; DoWhile[procedure_, test_] := While[procedure; test]


6

Here are two possibilities. First, use MovingMap: ClearAll[av]; av[{l_, 0, r_}] := (l + r)/2; av[{_, m_, _}] := m; and then smoothMM[list_] := Join[{First@list}, MovingMap[av, list, 3], {Last@list}] or, you can use in-place assignments: smooth2[list_] := Module[{copy = list, pos = Flatten[Position[list[[2 ;; -2]], 0]] + 1 }, copy[[pos]] = (copy[[...


6

Normal[SparseArray[{{i_, j_} /; j != i :> 1/(Sin[i] - Sin[j])}, {5, 5}]] Non-zero diagonal, e.g. Pi: Normal[SparseArray[{{i_,i_} -> Pi, {i_, j_} /; j != i :> 1/(Sin[i] - Sin[j])}, {5, 5}]]


6

You can replace your subopt initialization and the For loop with: subopt = {x, y} /. FindMinimum[#, {x}, {y}][[2]] & /@ subdtotal Or using Map explicitly {x, y} /. Map[FindMinimum[#, {x}, {y}][[2]] &, subdtotal]


6

You don't actually need to put it in a loop. Mathematica has many other cleaner/faster/shorter ways of implementing this kind of thing. I'll give you three: A Do loop (which you asked for, so it wouldn't be much of an answer if I didn't). An alternative using Map (or /@), which shows up all over the place and is probably one of the most useful Mathematica ...


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