6

If I have two sets of data say, x={1,2,3} and y=(4,5,6}, and I wanted to make a table T = {{1,4},{2,5},{3,6}}, how would I do so by using x and y and not just typing out the whole table? Is there any way that I can make a table by doing something like Table[x,y] after specifying the vectors x and y?

I'm asking because I want to reference the x values when I plot a fitted line.

bmf
  • 15,157
  • 2
  • 26
  • 63
mathperson
  • 61
  • 1

4 Answers4

8

Some ways of doing it:

With

x = {1, 2, 3};
y = {4, 5, 6};

all of the following

Thread[{x, y}] // MatrixForm
Transpose[{x, y}] // MatrixForm
Inner[List, x, y, List] // MatrixForm
MapThread[List, {x, y}] // MatrixForm
Table[{x[[i]], y[[i]]}, {i, 1, Length[x]}] // MatrixForm
Partition[Riffle[x, y], 2] // MatrixForm
Transpose[ArrayFlatten[{x, y}], {2, 1}] // MatrixForm
Function[, {##}, Listable][x, y] // MatrixForm
Quiet@Factor[x, y] /. Factor -> List // MatrixForm

a variant of the last is:

foo[x, y] /. foo -> List // MatrixForm

Edit 1: there'a a new command called ArrayReduce

ArrayReduce[Dot, {x, y}, 1] // MatrixForm

Edit 2: and another way

Multicolumn[Flatten@ArrayReshape[{x, y}, {2, 3}], 
   2][[1]] // MatrixForm

Edit 3: special thanks to @user1066 for the valuable comment. One can observe how the following behaves

ArrayReduce[f, {x, y}, 1] // MatrixForm

and from the above we can deduce that the following two commands give the desired output

ArrayReduce[Join, {x, y}, 1] // MatrixForm
ArrayReduce[Union, {x, y}, 1] // MatrixForm

All of the above give:

mat

bmf
  • 15,157
  • 2
  • 26
  • 63
  • @user1066 many thanks for the feedback. the comment is implemented in the answer – bmf Jan 31 '23 at 02:13
7

This is what you have

(mat = {{1, 2, 3},{4, 5, 6}}) // MatrixForm

Mathematica graphics

And this is what you want

(matWanted = {{1, 4}, {2, 5}, {3, 6}}) // MatrixForm

Mathematica graphics

Now if you have the first form, how to obtain the second form from it? What is the name of the operation to do it?

Nasser
  • 143,286
  • 11
  • 154
  • 359
5

Another way:

Diagonal@Outer[List, x, y] // MatrixForm

enter image description here

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
3

No one seems to have mentioned Flatten

Flatten[{x,y},{{2}}]

(* {{1, 4}, {2, 5}, {3, 6}} *)

When dealing with 'ragged' arrays, this method may be advantageous:

Compare:

Flatten[{x, Append[y, 100]},{{2}}]

Transpose[{x, Append[y, 100]}]

(* {{1, 4}, {2, 5}, {3, 6}, {100}}

Transpose::nmtx: The first two levels of {{1, 2, 3}, {4, 5, 6, 100}} cannot be transposed.

*)

The documentation for Flatten also gives an example of how to 'Do a "transpose" on a ragged array', and this usage of Flatten is very well explained here by Leonid Shifrin

user1066
  • 17,923
  • 3
  • 31
  • 49