5
$\begingroup$

I currently have a two lists. The first list contains independent variables $x$, and the second list contains dependent variables in the form of $\{\{f[1][x]\},\{f[2][x]\},...,\{f[n][x]\}\}$.

I want to combine them in the form $$\{\{\{x1,f[1][x1]\},\{x2,f[1][x2]\},...,\{xn,f[1][xn]\}\},\{\{x1,f[2][x1]\},\{x2,f[2][x2]\},...,\{xn,f[2][xn]\}\},...,\{\{x1,f[n][x1]\},\{x2,f[n][x2]\},...,\{xn,f[n][xn]\}\}\}$$ ...an easy format for ListPlot.

For some example data:

a = Range[10];
b = a^2;
c = (a + 1/2)^2;
fa = {b,c};

Now one can easily do this with Table:

Table[{a[[j]], fa[[i, j]]}, {i, Length[fa]}, {j, Length[c]}]

but knowing Mathematica's many functions I thought there might be an easier way. I tried this as well:

Transpose@MapThread[Tuples@{{#1}, #2} &, {a, Transpose@fa}]

but with the multiple Transpose calls, I figured there would be a slight performance hit. And there was (2.854 vs 3.261 seconds for vectors with 1MM elements on my machine).

Is there an easier and more efficient way to combine these lists?

$\endgroup$
3
  • $\begingroup$ So in your notation, f[1][x1] really means f[[1,1]] and not SubValues? $\endgroup$
    – rm -rf
    Nov 28, 2012 at 20:33
  • $\begingroup$ @rm-rf, Nah, it just means f[1] is a data vector that corresponds to the x-values. f[2] is another data vector not related to f[1]. Etc. Feel free to suggest another notation. $\endgroup$
    – kale
    Nov 28, 2012 at 20:38
  • $\begingroup$ Also MapThread[List, {a, #}] & /@ fa will do the job. $\endgroup$
    – garej
    Dec 26, 2015 at 12:02

1 Answer 1

7
$\begingroup$
Thread[{a, #}] & /@ fa

or

Inner[List, a, #, List] & /@ fa
$\endgroup$
3
  • $\begingroup$ Yep. I love how I come up with Transpose@MapThread[Tuples@{{#1}, #2} &, {a, Transpose@fa}] but not Thread[{a,#}]&/@fa. Sigh. In any regards, the Thread method is 7.5x faster and the Inner method is 12x faster than the MapThread I suggested. Thanks! $\endgroup$
    – kale
    Nov 28, 2012 at 23:29
  • $\begingroup$ @kale could you say how fast is Array in your setup? $\endgroup$
    – au700
    Nov 29, 2012 at 1:26
  • $\begingroup$ @au700, You'll have to elaborate. Not sure I see a way to use Array to solve the problem... $\endgroup$
    – kale
    Nov 29, 2012 at 2:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.