I have gone through some reference material but I am not getting really good links that will help me grow understanding of pure functions,patterns and list manipulations combined together
. Most of the examples referred in documentation are for single list(without sublists).
For example, say from a list I wanted to pick first element of every sublist, say,fi = FactorInteger[12]
so I used
Table[fi[[i, 1]], {i, 1, Length[fi]}]
I try to do everything with Table
. Though it should be achievable via other simple ways too. Can someone please put some examples where one can get to learn how to access data from lists of sublists and how to decompose it. This might sound pretty trivial to lot of people but I couldn't find books and links either that can give insight into combining these Mathematica features together.
Answer
I'm going to answer this as I think it is helpful to gather multiple methods in one place, and such a list is not, as far as I know, easily found in the documentation.
a = FactorInteger[269325]; (* sample data *)
a[[All, 1]]
First[a\[Transpose]]
a.{1, 0}
First /@ a
# & @@@ a
#[[1]] & /@ a
All lines output: {3, 5, 7, 19}
.
a[[All, 1]]
is I believe the fastest general method, and should usually be your first choice.
First[a\[Transpose]]
(this looks better in a Notebook) is a fast method for rectangular data.
a.{1, 0}
shows a numeric method using Dot
that is applicable to arrays of known dimensions, such as the output of FactorInteger
.
First /@ a
is probably the most explicit and easiest to read.
# & @@@ a
illustrates the use of pure functions and Apply
at level one.
Be aware that the latter methods are often slower because they will unpack.
Here are timings for these methods on packed data:
SetAttributes[timeAvg, HoldFirst]
timeAvg[func_] := Do[If[# > 0.3, Return[#/5^i]] & @@ Timing @ Do[func, {5^i}], {i, 0, 15}]
a = RandomInteger[1*^9, {500000, 2}];
a[[All, 1]] // timeAvg
First[a\[Transpose]] // timeAvg
a.{1, 0} // timeAvg
First /@ a // timeAvg
# & @@@ a // timeAvg
#[[1]] & /@ a // timeAvg
0.00512
0.0012976
0.011984
0.04304
0.2122
0.04492
And unpackable data:
a = RandomChoice[{Pi, "x", 1}, {500000, 2}];
a[[All, 1]] // timeAvg
First[a\[Transpose]] // timeAvg
a.{1, 0} // timeAvg
First /@ a // timeAvg
# & @@@ a // timeAvg
#[[1]] & /@ a // timeAvg
0.01684
0.02308
0.2122
0.078
0.0968
0.1592
Comments
Post a Comment