3
$\begingroup$

I use the following code to create a list of input parameters:

xa = Range[-1, 1, 0.05];
ya = Range[-1, 1, 0.05];
xb = Range[-1, 1, 0.05];
yb = Range[-1, 1, 0.05];

crazylist = Tuples[{xa, xb, ya, yb}];

However, later these the set of x & y values are used in a symmetric way, that is, for instance:

xa = 0.79
xb = 0.14

ya = 0.84
yb = 0.91

and

xa = 0.84
xb = 0.91

ya = 0.79
yb = 0.14

give exactly the same result. Is there any way to get rid of these duplicates. In other words, to delete/not create all but one of these combinations? This could save a lot of calculation time.

I couldn't find a proper solution for this problem online (or didn't understand how to adapt to my problem.)

Best, Fabian

$\endgroup$
1
$\begingroup$

Maybe this does what you are looking for?

A helper function; given a vector of indices $k_1,\dotsc,k_m$ and an integer $n$, it computes vectors of indices $i_1,\dotsc,i_m$ and $k_1,\dotsc,j_m$ so that the $k_\alpha$-th entry in a upper triangular $n\times n$-matrix $A$ is $A_{i_\alpha, j_\alpha}$.

LinearToTriangularIndexing[k_?VectorQ, n_Integer] := Module[{i, j},
   i = n - 1 - Floor[Sqrt[4. n (n - 1) - 8. k + 1.]/2.0 - 0.5];
   j = Subtract[
     k + i + Quotient[Subtract[n + 1, i] Subtract[n, i], 2], 
     Quotient[n (n - 1), 2]];
   {i, j}
   ];

Now we generate the coordinates list for the x which contains all point of an $n \times n$ grid. Arranging pairs of elements in x in a $n^2 \times n^2$ matrix, we only want to read off the entries in the upper triangle.

x = Tuples[{xa, xb}];
n = Length[x];
{i, j} = LinearToTriangularIndexing[Range[n (n - 1)/2], n];
pairs = Join[x[[i]], x[[j]], 2];

This does not include the diagonal entries. You may add them with

pairs = Join[ pairs, Join[x,x,2]];
$\endgroup$
  • $\begingroup$ Thanks a lot, this did exactly what I wanted! $\endgroup$ – Fabian Apr 5 at 17:27
  • $\begingroup$ You're welcome. $\endgroup$ – Henrik Schumacher Apr 6 at 13:13
3
$\begingroup$
pts = Subdivide[-1, 1., 40]  (* your example has this the same for all *)
prs = Tuples[{pts, pts}]  (* all possible pairs *)
sames = Join[#, #] & /@ prs
xxyy01 = Subsets[prs, {2}]  (* all possible pair of different pairs *)
all=Join[Catenate /@ xxyy01, sames]
Whatever @@@ all  (* do whatever you want with each *)
$\endgroup$
  • $\begingroup$ Unfortunately, my mathematica version appears to be too old for "subdivide" and "catenate" :-( $\endgroup$ – Fabian Apr 5 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.