Mathematica 9 is now available
Student Support Forum
Student Support Forum: 'help with loops' topicStudent Support Forum > General > "help with loops"

Next Comment >Help | Reply To Topic
Author Comment/Response
10/13/09 07:59am

Hi all,

This is my first attempt at programming (in any language!), so I would appreciate any input on the following task. I have searched through the help files and manual extensively, but I am not sure what to look for exactly...

The attached file includes the code I have generated so far.

Many many thanks!

I have couples consisting of one male and one female individual, respectively m1 and f1. Each individual is assigned one strategy for two behaviours. The first behaviour is A, with strategies a1 and a2; the second behaviour is B, with strategies b1 and b2.

I need to generate a table consisting of all the possible combinations of the two behaviours, ie:

m1      f1
a1 b1   a1 b1
a1 b1   a1 b2
a1 b1   a2 b1
a1 b1   a2 b2

So I have:

A = {a1, a2};
B = {b1, b2};

For[i = 1, i <= Length[A], i++,
For[j = 1, j <= Length[B], j++,
For[k = 1, k <= Length[A], k++,
For[l = 1, l <= Length[B], l++,
Print[{{A[[i]], B[[j]]}, {A[[k]], B[[l]]}}]]]]]

My first question is, how do I write this more compactly? This would be handy because in reality each row will correspond to a cluster comprising up to 2 males and 2 females, thus the code becomes:

For[i = 1, i <= Length[A], i++,
For[j = 1, j <= Length[B], j++,
For[k = 1, k <= Length[A], k++,
For[l = 1, l <= Length[B], l++,
For[m = 1, m <= Length[A], m++,
For[n = 1, n <= Length[B], n++,
For[o = 1, o <= Length[A], o++,
For[p = 1, p <= Length[B], p++,
Print[{{A[[i]], B[[j]]}, {A[[k]], B[[l]]}, {A[[m]], B[[n]]}, {A[[o]],

As well, I will need to be able to refer to the individual rows in the output, for example as row1, row2, etc. I could not figure out how to do this since I don't know in advance how many rows I will have!

This will allow me to refer to the strategy for a particular behaviour for a given individual, for example row1[[1,1]], and to apply conditional rules, for example if row1[[1,1]]=a1 don't add a second female to the cluster.

Attachment: question.nb, URL: ,

Subject (listing for 'help with loops')
Author Date Posted
help with loops Arual 10/13/09 07:59am
Re: help with loops Peter Pein 10/23/09 10:38am
Re: Re: help with loops Arual 10/26/09 06:16am
Next Comment >Help | Reply To Topic