Hot answers tagged

33

This is a community wiki answer. Feel free to improve it. Introduction RawArray is an atomic array type that can hold data in any of the following formats: "Integer8", "UnsignedInteger8", "Integer16", "UnsignedInteger16", "Integer32", "UnsignedInteger32", "Integer64", "UnsignedInteger64", "Real32", "Real64", "Complex64", "Complex128" (Some aliases can ...


22

These are ancient routines I have been using a long time ago. As a matter of fact, it's been so long that I do not even remember if I wrote them or simply shamelessly took them from some other source. Back at the time the only sources I had at my disposal where The Mathematical Journal (prior to 1998 or 1999), Bahder's wonderful book (which is the most ...


22

VectorQ is specially optimized with the following functions The following were tested in M11.3 unless stated otherwise. Past versions may behave differently. NumberQ, NumericQ (verified in M10.0) MachineNumberQ IntegerQ Developer`MachineRealQ, Developer`MachineIntegerQ, Developer`MachineComplexQ (verified in M10.0 but see bug below) Internal`...


20

I always use TimeSeries for these kinds of problems, since it avoids having to worry about indices too much, gives you good control over resampling and you have a whole load of useful functions dt = 0.05; {ts1, ts2} = TimeSeries[TimeSeriesResample[#, dt, ResamplingMethod -> {"Interpolation", InterpolationOrder -> 1}]] & /@ {data1, data2}; ...


19

list = {1, 2, 3, 4, 5, 6, 7, 8}; Partition[list, UpTo[3]] {{1, 2, 3}, {4, 5, 6}, {7, 8}}


17

Use SparseArray. SparseArray[List /@ {2, 5, 9} -> 1] // Normal (* {0, 1, 0, 0, 1, 0, 0, 0, 1} *)


16

Not as simple as the other solutions, but the linear-algebraic treatment might be convenient in some applications: m = Partition[Range[12], 3]; Add column 2 and column 3, and store result in column 3: m.SparseArray[{Band[{1, 1}] -> 1, {1, 3} -> 1}, ConstantArray[Last[Dimensions[m]], 2]] Add row 2 and row 3, and store result in row 2: SparseArray[{...


14

There are many solutions but not so many that Solve wouldn't be the right way to go. Since the task has been changed I slightly refine the solution. First we find all integer solutions satisfying 1 <= x <= 9 with Solve: sol1 = {z, w, e, i, v, r, f, u, n} /. Solve[ Join[{1000 z + 100 w + 10 e + i + 1000 v + 100 i + 10 e + r == 10000 f + ...


13

There are some internal, undocumented functions for row and columns operations: (* in-place(!) transformation of the matrix *) Statistics`Library`MatrixRowTranslate[matrix, vector] Statistics`Library`MatrixRowTimes[matrix, vector] Statistics`Library`MatrixRowAffineTransform[matrix, vector, vector] (* mat, times, xlate *) Statistics`Library`...


13

Here is a version that seems pretty fast and does not involve compiled code: ClearAll[getMask]; getMask[arr_, set_] := Module[{max = Max[arr], min = Min[arr], inds, dim, lset}, lset = Pick[set, UnitStep[set - min]*UnitStep[max - set], 1]; dim = max - min + 1; inds = SparseArray[{}, dim]; inds[[lset - min + 1]] = 1; inds[[arr - min + 1]]...


12

I'd use FixedPoint: FixedPoint[ ArrayFlatten, Sigma[1, 1]] We have: ArrayFlatten[ ArrayFlatten[ ArrayFlatten[ ArrayFlatten[ Sigma[1, 1]]]]] == FixedPoint[ ArrayFlatten, Sigma[1, 1]] True and FixedPoint[ ArrayFlatten, Sigma[1, 1]] // MatrixForm


12

Update: here Table is faster and more user-friendly then Array. mat[n_] := LowerTriangularize@Table[2 (1 + Boole[j > 1]) (i - 1) Mod[i + j, 2], {i, n}, {j, n}]; mat[10] // MatrixForm It is fast and the result is packed array mat[1000] // Developer`PackedArrayQ // AbsoluteTiming (* {0.142522, True} *)


11

Ad. I These should be the most efficient and tersest Ceiling[ Range @ 27 / 3 ] or Array[ Ceiling[#/3] &, 27] yield {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9} they both can be tersely written in the Front End (see details of Ceiling) as: or Ad.II For the second problem there are many approaches, here is ...


11

To sort by a specific element use a pure function with the number in question. For your case (the second element) just do: SortBy[a, #[[2]] &] {{7, 1, 4}, {1, 2, 3}, {12, 4, 8}, {3, 5, 6}, {10, 7, 1}} You can also use Sort like this: Sort[a, #1[[2]] < #2[[2]] &]


11

This seems to be a case for OrderlessPatternSequence tT = {{7, 1, 2}, {7, 2, 3}, {7, 3, 8}, {7, 1, 6}}; MemberQ[tT, {OrderlessPatternSequence[1, 2, 7]}] True Or define a function to wrap the second argument of MemberQ: foo = {OrderlessPatternSequence @@ ##}&; MemberQ[tT, foo @ {1,2,7}] True MemberQ[tT, foo @ #] & /@ {{1, 2, 7}, {3, 8, 7},{...


11

I would suggest reading it with numpy and not Mathematica. It seems to me that this is not an exchange format. It is a format meant to be used only by numpy. Mathematica 12.0 has significantly improved ExternalEvaluate, and now you can transfer data from Python to Mathematica quite efficiently. ExternalEvaluate["Python", "import numpy as np x = np.arange(...


11

This is precisely what SparseArray is good for: SparseArray[data[[All, 1 ;; 2]] -> data[[All, 3]]]


11

Map will iterate over the list and apply some function element-wise. In your case, list is a 2D-array, so Map will iterate over the the elements of list, which are {100,100} and {200,200}. These are the values that are then applied to Transpose, which will clearly fail. To better illustrate this, you can use some undetermined function f to see what's going ...


10

Because data1 and data2 have an extra set of curly brackets, it is necessary to remove the extra set before generating interpolating functions. int1 = Interpolation[Flatten[data1, 1]]; int2 = Interpolation[Flatten[data2, 1]]; The difference then can be computed and plotted: Plot[{int1[t], int2[t + .35], int1[t] - int2[t + .35]}, {t, 1105, 1134}] The ...


10

Join[list, toappend, 2] MapThread[Join, {list, toappend}] Join @@@ Transpose@{list, toappend} (* thanks: AccidentalFourierTransform *) Flatten /@ Transpose[{list, toappend}] MapIndexed[Join[#, toappend[[#2[[1]]]]] &, list] MapIndexed[Flatten[{#, toappend[[#2[[1]]]]}] &, list] Flatten[{list[[#]], toappend[[#]]}]& /@ Range[Length @ list] all give ...


9

A very neat one liner does exist, and it's done using the 3 argument form of Array. Observe the following: Array[# &, 5, {{0, 1}, {1, 1}}] (* {{0, 1}, {1/4, 1}, {1/2, 1}, {3/4, 1}, {1, 1}} *) where the 5 is your desired number of inserts (3) plus the endpoints (2). Array automatically does the insertion in the appropriate coordinates. Now you just need ...


9

Here's a solution that lets you define terms/sum/entries/constraints generally. Spits out a table where rows are valid values for the corresponding column variables with verification of solutions. ClearAll[z, w, e, i, v, r, f, u, n]; (* Define alphabet,terms, and sum *) vars = {z, w, e, i, v, r, f, u, n}; term1 = {z, w, e, i}; term2 = {v, i, e, r}; sum = {...


9

Here is a simple method that seems to be somewhat faster than yours on unpackable data: colDrop[array_, drop_] := Module[{m = array}, m[[All, drop]] = Sequence[]; m] Test: data = Range /@ RandomInteger[{15, 50}, 500000]; data = Map[FromCharacterCode, data + 37, {2}]; colDropper[data, {1, 3, 5, 8, 10, 11}] // Timing // First colDrop[data, {1, 3, 5, 8, ...


9

Q1 Join[a[[;; , ;; 1]], b, a[[;; , 2 ;;]], 2] One may want to create function insCol[a_, b_, n_] := Join[a[[;; , ;; n - 1]], b, a[[;; , n ;;]], 2] insRow[a_, b_, n_] := Join[a[[;; n - 1]], b, a[[n ;;]]]


9

Using the same variable names. The separation can be approximated using FindPeaks. I have used on the distinctive three middle peaks. lp1 = ListPlot[data1, Epilog -> {Red, PointSize[0.03], Point@(p1 = Extract[data1[[1]], List /@ FindPeaks[data1[[1, All, 2]]][[All, 1]]])}, Frame -> True, ImageSize -> 400]; lp2 = ...


9

centroid = {Total[data, {1}], Total[data, {2}]}.Range[57]/Total[data, -1] (* {63951/3623, 136282/3623} *) MatrixPlot[data, DataReversed -> True, Epilog -> Point[centroid - 0.5]]


9

Update after discussions in comments I've revised my code to use Replace with a level spec, and to create rules only from list2, since the latter list can be much smaller than the first list. This provides a speed boost of about 50%. update[l1_,l2_] := Module[{p, q, r=l1}, p = Replace[ l1[[All,;;2]], Dispatch @ Thread @ Rule[l2[[All,;;2]...


9

With the conditions that each row must not contain duplicates and each column must not contain duplicates, construct a random solution matrix by rows. The first row is a random sample of the permutations of gps. The following rows are selected at random from the remaining permutations that satisfy the conditions. There are two questions to consider from ...


9

ComponentMeasurements and MorphologicalComponents ClearAll[cf1] cf1 = ComponentMeasurements[MorphologicalComponents[Image@{#}], "Count"][[All, -1]] & /@ # & /@ ({#, Transpose@#}) &; Using cf1 with the barcode image in OP: img = BarcodeImage["my test", "QR", 10]; data = 1 - ImageData[img]; cf1 @ data // Panel /@...


9

It seems that using ArrayReshape and modifying, if needed, the last entry to remove trailing zeros is faster than using Partition or using Inactive @ Nothing padding: ClearAll[f1, f2, f3, f4] f1 = Partition[#, UpTo[#2]] &; (* from Okkes's answer *) f2 = Partition[#, #2, #2, 1, {}] &; f3 = Activate @ ArrayReshape[#, {Ceiling[Length[#]/#2], #2}, ...


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