Message Boards Message Boards

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

[?] Create a loop in two elements?

Posted 7 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
Posted 7 years ago

Thanks a lot!!

POSTED BY: Ghady Almufleh

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

There are a lot of solutions. In your code there is only one error. You must remove i from AppendTo[]:

In[6]:= 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]]}]]]

Out[8]= {}

In[10]:= result

Out[10]= {{1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 1}, {2, 2}, {2, 
  3}, {2, 4}, {2, 5}, {3, 1}, {3, 2}, {3, 3}, {3, 4}, {3, 5}, {4, 
  1}, {4, 2}, {4, 3}, {4, 4}, {4, 5}, {5, 1}, {5, 2}, {5, 3}, {5, 
  4}, {5, 5}}

But you may obtain the same result in other ways, e.g.:

In[13]:= result = 
 Table[{x[[i]], y[[j]]}, {i, Length[x]}, {j, Length[y]}]

Out[13]= {{{1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}}, {{2, 1}, {2, 
   2}, {2, 3}, {2, 4}, {2, 5}}, {{3, 1}, {3, 2}, {3, 3}, {3, 4}, {3, 
   5}}, {{4, 1}, {4, 2}, {4, 3}, {4, 4}, {4, 5}}, {{5, 1}, {5, 2}, {5,
    3}, {5, 4}, {5, 5}}}
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract