Hi Guys, i have a forloop problem.
I have a nxs matrix, where s=sum((k),k=1..n-1), so when n=3, s=3, when n=4,s=6 and so on.
I need to code each column number lexicographically for cartesian pair (i,j) where i<j, so when n=3, the columns would be
(1,2),(1,3),(2,3)
and when n=4 we have
(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)
.
I am able to create this lexicographical order independently but where i am stuck, and wondering whether it can be done is to associate the cartesian pair, with the true column number, so with the previous example
1 2 3 4 5 6
(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)
Is it possible?
not tricky, and no loops!
Here is how I would approach this problem. First, s is the sum of the first n-1 integers:
s := n -> n*(n-1)/2; 1 n -> - n (n - 1) 2The list of ordered pairs (i,j) with i<j, i=1..n, and j=1..s can be constructed with
P := n -> [seq( seq( [r,c], c=r+1..s(n) ), r=1..n )]; P(3); [[1, 2], [1, 3], [2, 3]] P(4); [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 3], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6], [4, 5], [4, 6]]To find the index in this list, use the member command with the optional third argument.
member( 1, [0,1,2], 'p' ); true p; 2These can all be put together in a single procedure, as follows:
LookUp := proc(e,S) local p; if not member(e,S,'p') then p:=0 end if; return p end proc: LookUp( [4,5], 5 ); 25 LookUp( [5,5], 5 ); 0You might want to have a different behavior when the element is not in the set. I chose to have the LookUp procedure return 0.
Does this do what you have requested?
Doug
Possible solution
A quick bit of code to get the sequence you had in your example would be the following:
[seq(seq([i, j], i = 1 .. j-1), j = 2 .. 4)];
If you want to place this inside of a Maple table structure, you could call
Test := table([seq(seq([i, j], i = 1 .. j-1), j = 2 .. 4)]);
which would allow you to call
Test[2]
[1,3]
Another option is to us an array which would be something like the following:
Test2 := Array([seq(seq([i, j], i = 1 .. j-1), j = 2 .. 4)]);
Test2[2]
[1,3]
Scott
Using a table
The association may also be obtained as follows: Define the procedure
Then, for instance,
t := assoc(4): t[1],t[2],t[3],t[4],t[5],t[6]; [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]Hi these loops are all
Hi these loops are all greats thanks!