Group Abstract Group Abstract

Message Boards Message Boards

0
|
6.5K Views
|
3 Replies
|
2 Total Likes
View groups...
Share
Share this post:

[?] Create a loop in two elements?

Posted 8 years ago

I have data for x and y, but I need to create a loop to get : for every element of x will be combined with all the elements of y . For example

If I have x={1,2,3,4,5} , y={1,2,3,4,5} and I need this result for {x,y} : {{1,1},{1,2},{1,3},{1,4},{1,5},{2,1},{2,2},{2,3},……………..{5,5}} , how can I create this loop? Below is my loop, but it doesn't give me any result!!

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

result = {}
For[i = 1, i <= Length[x], i++,
 For[j = 1, j <= Length[y], j++,
  AppendTo[result, {x[[i]], y[[j]], i}]]]

Thanks!!

POSTED BY: Ghady Almufleh
3 Replies

I would strongly recommend, not to use Append/AppendTo and For loops, there are much faster, shorter, better code available. Here are 4 ways:

x={1,2,3,4,5}
y={6,7,8,9,10}

Tuples[{x,y}]
Join@@Outer[List,x,y,1]
Join@@Table[{i,j},{i,x},{j,y}]
Reap[Do[Sow@{i,j},{i,x},{j,y}]][[2,1]]
POSTED BY: Sander Huisman
Posted 8 years ago

Thanks a lot!!

POSTED BY: Ghady Almufleh
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard