The code below assigns a sequential number to each item in a list of lists. The code is written in a procedural programming style.
Seeking recommendations for re-writing this in functional programming style that would be:
- more compact
- readable to intermediate level Mathematica users
All recommendations are welcome.
vec1 = {a, b, c, d};(* data vector*)
vec2 = {a, b, c, d, e, f};(* data vector*)
vec3 = {a, b, c};(* data vector*)
allVecs = {vec1, vec2, vec3} (*sample data. Both the number of vectors and the length of each vector are arbitrary*)
nEach = Length@# & /@ allVecs;(*length of each data vector*)
allIndices = Range@Total@ nEach;(*list of indices, one index for each entry in the sample data*)
lPos = FoldList[Plus, 0, nEach];(*start and stop positions of each data vector. start positions are 0 offset*)
iA = {}; (*this list is the goal: sequential numbering of each data item*)
iInd = {};(*list of indices corresponding to each data vector*)
For[ i = 1, i <= Length@nEach, i++,
AppendTo[iInd, allIndices[[lPos[[i]] + 1 ;; lPos[[i + 1]]]] ];
AppendTo[iA, Transpose[{iInd[[i]], allVecs[[i]]}] ];
]
iInd;
iA (*result*)
(* data: {{a, b, c, d}, {a, b, c, d, e, f}, {a, b, c}} *)
(* result: {{{1, a}, {2, b}, {3, c}, {4, d}}, {{5, a}, {6, b}, {7, c}, {8,
d}, {9, e}, {10, f}}, {{11, a}, {12, b}, {13, c}}} *)
Attachments: