# Reading list data like a loop

Let's assume, I have a data set like:

data1 = {{{a1, b1, c1}, {d1, e1, f1}}, {{a2, b2, c2}, {d2, e2, f2}}, ...,
{{a20, b20, c20}, {d20, e20, f20}}}.


This can be seen as:

data1 = {X1, X2, ..., X20}. where Xi = {{ai, bi, ci}, {di, ei, fi}}


Now I want to use eachXiand perform an operation R (lets say R is a Matrix) on that.

How can I do that?

• You actually don't want to do that in a loop. Instead, you want to Map a function over data1, Try Map[func, data1] to see what the result would look like. Besides, isn't this a very similar question to your previous one? Jun 9, 2018 at 23:22
• Hi Marco, thanks for your comment. Maybe I did not explain the problem properly before. Please have a look at the updated one and suggest if you feel. Jun 10, 2018 at 0:27
• Isn't this question very similar to your other one? Jun 10, 2018 at 1:11
• Yes, I agree..and trying to solve the problem.. Jun 10, 2018 at 1:19
• What is the dimension (or say shape) of R? Jun 10, 2018 at 5:29

You can use Map (shorthanded as /@; this function is one of the typical that help one avoid explicit loops):

#.R & /@ data1


However, the best might be just using Dot (.):

data1.R


As a check, one can run codes below:

data1 = RandomInteger[10, {20, 2, 3}];
R = RandomInteger[10, {3, 3}];
#.R & /@ data1 == data1.R


which returns True.

You really only need Map (/@ as binary operator) and, in many cases, a custom function expressing what you want to do with each of sublists at level 1. Mathematica's ability to match argument patterns with the data given to a function will take care to the rest.

Here are the most common use-cases.

Function works directly on the sublists at level 1.

data =
{{{a1, b1, c1}, {d1, e1, f1}},
{{a2, b2, c2}, {d2, e2, f2}},
{{a20, b20, c20}, {d20, e20, f20}}};

Transpose /@ data

{{{a1, d1}, {b1, e1}, {c1, f1}},
{{a2, d2}, {b2, e2}, {c2, f2}},
{{a20, d20}, {b20, e20}, {c20, f20}}}


Function works directly on the two lists contained in the sublists at level 1.

f[{l1_List, l2_List}] := l1^l2
f /@ data

{{a1^d1, b1^e1, c1^f1}, {a2^d2, b2^e2, c2^f2}, {a20^d20, b20^e20, c20^f20}}


Function works directly on the elements of the two lists contained in the sublists at level 1.

g[{{a_, b_, c_}, {d_, e_, f_}}] := d Sin[a] + e Cos[b] + f Tan[c]
g /@ data

{e1 Cos[b1] + d1 Sin[a1] + f1 Tan[c1],
e2 Cos[b2] + d2 Sin[a2] + f2 Tan[c2],
e20 Cos[b20] + d20 Sin[a20] + f20 Tan[c20]}


When you want to iterate through a list of data, one element at a time, you can use Table or Do, depending on whether you want to collect the results for each element or just do something for each.

In[67]:= data = {a, b, c};

In[68]:= Table[ E^x, {x, data}]

Out[68]= {E^a, E^b, E^c}

In[69]:= Do[Print[x] , {x, data}]

During evaluation of In[69]:= a

During evaluation of In[69]:= b

During evaluation of In[69]:= c