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]


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


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

(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

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

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

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

Define random using SetDelayed so that each time it is used it gives a different random vector: lngth = 834; rndm := RandomVariate[NormalDistribution[0, dt^.5], lngth - 1] Instead of using a loop you can use Prepend[Accumulate[rndm] gamma + mu dt + .0158, .0158] to get a random vector of length 834. You can use the above with Table to generate as many ...


6

First, define an $ n $-by-$ n $ symmetric matrix of all zeros and ones: n = 5; a = RandomInteger[{0, 1}, {n, n}]; a = UpperTriangularize[a] + LowerTriangularize[Transpose[a]] - DiagonalMatrix[Diagonal[a]] Now define a function that randomly changes two of the elements while maintaining symmetry: change[x_] := Module[{b = x}, {...


6

This is simply a translation of the recursive rules indicated: Block[ {step = 0.001, p = 1000}, NestList[ Apply[{#1 + step, ((#2 + 273.15) - p*(#1 + step)) - 273.15} &], {0, 50}, 6 ] ] (* Out: {{0, 50}, {0.001, 49.}, {0.002, 47.}, {0.003, 44.}, {0.004, 40.}, {0.005, 35.}, {0.006, 29.}} *)


6

Join @@ MapAt[ConstantArray[1, 4] &, Partition[f, 4], {2 ;; ;; 2}] With[{mask = 1 - Mod[Quotient[Range@16, 4, 1], 2]}, mask f + 1 - mask] SubsetMap[1 & /@ # &, f, Join @@ Partition[Range[16], 4, 8, 5]] With[{p = Join @@ Partition[Range[16], 4, 8]}, Normal@SparseArray[p -> 3 p^2, 16, 1]] all give {3, 12, 27, 48, 1, 1, 1, 1, 243, 300, 363, ...


6

Try n = 20; M = Table[If[i == j, -(1 + 2/h^2), If[Abs[i - j] == 1, 1/h^2 + x1/(2 h), 0]], {i, 1, n}, {j, 1, n}] or also M = SparseArray[{Band[{1, 1}] -> -(1 + 2/h^2), Band[{2, 1}] -> 1/h^2 + x1/(2 h), Band[{1, 2}] -> 1/h^2 + x1/(2 h)}, {n, n}] NOTE Now for $x_k, k=1,\cdots, n$ we can use M = SparseArray[{{i_, i_} -> -(1 + 2/h^2), {n, n - 1} -&...


5

You might find this interactive version educational. With[{n = 5}, DynamicModule[{m = ConstantArray[0, {n, n}], nextM}, nextM[] := Module[{i, j}, {i, j} = RandomInteger[{1, n}, 2]; m[[i, j]] = m[[j, i]] = RandomInteger[]]; Manipulate[ m // MatrixForm, Row[{Invisible @ Button["********", {}], Button["Next", nextM[]]...


5

You can use Inactive to postpone the SetDelayed operation until after the RHS has been defined. Here is an example: Clear[Subscript]; sol = Subscript[x, i_][t] -> t^i; n = 10; Activate @ Table[ Inactive[SetDelayed][ Subscript[X,i][t_], Subscript[x,i][t]/.sol ], {i, n} ]; Check: Subscript[X, 4][2] 16


5

Mathematica has a lot of prime functionality built in. In particular PrimeQ[x] gives True if x is prime and false otherwise, and PrimePi[x] counts the number of primes less than or equal to x. So, it seems like you want something like numPrime[n_] := If[PrimeQ[n], PrimePi[n], Null] so that numPrime[17]=7 and numPrime[21] is Null (or you could print ...


5

I think both your code and your Wolfram|Alpha query gave the wrong answer. Here is how I would write a function to generate a rational value from a list of continued fraction terms. fromTerms[terms_List] := Fold[#2 + 1/#1 &, Reverse @ terms] This is nice, concise, functional code and set = {1, 2, 3, 4, 5}; fromTerms[set] gives 225/157 which we ...


5

bill = {3, -5, 2, -12, -4, -1, -8, 10}; Total[Select[bill, # > 0 &]] An even shorter way, from this question, is Total[Select[bill, Positive]] The answer is 15. I believe that covers the OP's request, but it might be something more complicated. On documentation, https://reference.wolfram.com/language/ref/Select.html


5

g[k_Integer] := 3 k^2 /; MemberQ[{1, 2, 3, 4}, Mod[k, 8, 1]]; g[k_Integer] := 1 /; MemberQ[{5, 6, 7, 8}, Mod[k, 8, 1]]; g /@ Range[256]


5

Clear["Global`*"] Continuing on with the suggestion by infinitezero to use recursion, use RSolve to find the general expression. ex[n_] = ex[n] /. RSolve[{ex[0] == 1, ex[n] == ex[n - 1] + (1/2)^n/n!}, ex[n], n][[1]] (* (Sqrt[E] Gamma[1 + n, 1/2])/Gamma[1 + n] *) The first several values are ex /@ Range[0, 10] *) (* {1, 3/2, 13/8, 79/48, 211/...


4

I wouldn't use a loop here, I would go with: Times @@ {1, 1, 1, -2, 1, 2} But if you really need a procedural approach use a For loop instead (even if it's probably not a good idea).


4

List={3, -5, 2, -12, -4, -1, -8, 10} There are many ways to do this in Mathematica, without using For. One way could be to first filter out the positive numbers, then call Total list = {3, -5, 2, -12, -4, -1, -8, 10}; positiveNumbersOnly = Cases[list, x_ /; Positive[x] -> x] (*{3, 2, 10}*) Total[positiveNumbersOnly] (* 15*) You can combine the ...


4

Using Table instead of For. SeedRandom[99] dat1 = Table[Table[RandomInteger[8], {6}], {6}]; dat2 = Table[Tally[dat1[[i]][[All]]], {i, 1, 6}]; wrapFn[x_List, yLimit_Integer] := If[Length[x] < yLimit, 100, 0] datOut = Table[wrapFn[dat2[[i]], 5], {i, 1, 6}] (* Out: {100, 0, 100, 100, 100, 0} *) Just if it helps the OP, with a pre-Fortran IV mind like ...


4

An improved version of kglr's answer, makes use of the fact that m only consists of 0 and 1: m = RandomInteger[{0, 1}, {31, 2754}]; mt = Transpose[m]; func = Composition[Length, Union, Plus]; c2 = 1 - (Outer[func, mt, 2 mt, 1] - 4 // UnitStep); // AbsoluteTiming (* {22.1601, Null} *) kglr's solution takes about 53 seconds. Tested on v12.1, Wolfram ...


4

Here are a couple small improvements, first! DeleteCases[list1, Alternatives @@ list2] is, if list2 is full of literals and not pattern objects, as is the case here, the same as Complement[list1, list2], which gives all those elements of list1 not in list2. Instead of accessing a whole table and recalculating len from scratch each time we pass through the ...


4

As alluded to in the comments, you have several issues in your code, most of which are easily solved with some basic understanding of Mathematica's syntax and a sharp eye: Your closing brackets are all in the end of your code, you should pay attention to where the for-loop should end and where it actually does end. As Henrik mentioned: You need to check the ...


4

Not a one-liner, but straightforward. z1 = Table[Table[3*k*k, {k, i, i+3}], {i, 1, 256, 8}]; z2 = Table[{1,1,1,1}, {i, 1, 256, 8}]; result = Riffle[z1,z2] // Flatten


4

What about defining this recursively? ex[0] = 1; ex[n_] := ex[n] = ex[n - 1] + 0.5^n/n!; The double assignment in the second line is very important. This causes all function calls to be evaluated only once. Once it has been initially evaluated, it will be saved in ex[n]. Table[{k, ex[k]}, {k, 1, 10}] // TableForm 1 1.5 2 1.625 3 1.64583 4 1.64844 5 ...


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