how to store the data from each loop into an array

2019-08-09 15:14发布

问题:

For[n = 1, n < 6, n = n + 1,
   For[m = 1, m < 6, m = m + 1, abc = doc[[n]];
   kk = doc[[m]];
   v =vector[abc, kk]; 
   vl = VectorLength[v]]]

I want to store the data from each loop into an array or table form. How can I do that?

回答1:

Try using a Table instead of two For loops. It returns a list of lists of the results (a matrix basically)

Table[
 abc = doc[[n]];
 kk = doc[[m]];
 v = vector[abc, kk];
 vl = VectorLength[v], {n, 1, 5}, {m, 1, 5}]


回答2:

It's not clear to me what data you want to save, but the general way to do this is to use Sow and Reap.

Reap[
  For[n = 1, n < 6, n = n + 1, For[m = 1, m < 6, m = m + 1,
    abc = doc[[n]];
    kk = doc[[m]];
    Sow[v = vector[abc, kk]];
    vl = VectorLength[v]]]
][[2, 1]]

This saves every value of v = vector[abc, kk]. The Part extraction [[2, 1]] returns only this list.

If you want to save multiple data sets, you can use tags within Sow:

Reap[
 For[n = 1, n < 6, n = n + 1, For[m = 1, m < 6, m = m + 1,
   abc = doc[[n]];
   kk = doc[[m]];
   Sow[v = vector[abc, kk], "v"];
   Sow[vl = VectorLength[v], "v1"]
 ]]
]

Here I omit the Part extraction. Output is in the from {body, {{data1, ...}, {data2, ...}}} where body is any output from the expression itself (Null in the case of For). Data sets appear in the order they were first sown to. You can get an explicit order of sets with another argument of Reap as follows:

Reap[
  For[ ... ],
  {"v1", "v"}
]

See the documentation for Reap for more options.