Consider the following two tables:
tab1 = RandomReal[{1, 2}, {10, 4}];
tab2 = RandomReal[{2, 3}, {10, 6}];
and "charges" each representing the corresponding two columns of the tables:
qvalsTab1 = (1 - RandomInteger[{0, 2}, Length[Transpose[tab1]]/2]);
qvalsTab2 = (1 - RandomInteger[{0, 2}, Length[Transpose[tab2]]/2]);
(i.e., qvalsTab1[[1]]
represents the first two columns of tab1
, and so on).
I would like to join distinct pairs of columns from both tab1
and tab2
with either opposite values of qval
or if both of qval
are zero, and then join the resulting tables. My dumb code looks as follows:
vals = {};
Do[vals =
Join[vals,
If[qvalsTab1[[i]]*qvalsTab2[[j]] == -1 || (qvalsTab1[[i]] == 0 &&
qvalsTab2[[j]] == 0),
Join[tab1[[All, i*{1, 2}]], tab2[[All, j*{1, 2}]], 2], {}]], {i,
1, Length[qvalsTab1]}, {j, 1, Length[qvalsTab2], 1}]
Do[vals =
Join[vals,
If[qvalsTab1[[i]]*
qvalsTab1[[j]] == -1 || (qvalsTab1[[i]] == 0 &&
qvalsTab1[[j]] == 0) && i != j,
Join[tab1[[All, i*{1, 2}]], tab1[[All, j*{1, 2}]], 2], {}]], {i,
1, Length[qvalsTab1]}, {j, 1, Length[qvalsTab1]}]
Do[vals =
Join[vals,
If[qvalsTab2[[i]]*
qvalsTab2[[j]] == -1 || (qvalsTab2[[i]] == 0 ||
qvalsTab2[[j]] == 0) && i != j,
Join[tab2[[All, i*{1, 2}]], tab2[[All, j*{1, 2}]], 2], {}]], {i,
1, Length[qvalsTab2]}, {j, 1, Length[qvalsTab2]}]
May I please ask you whether there is a more elegant and faster solution (in reality, these tables are very long and the number of columns may be arbitrary) for this exercise?
(qvalsTab2[[i]] == 0|| qvalsTab 2[[j]] == 0)
in the last Do[...] be(qvalsTab2[[i]] == 0 && qvalsTab2[[j]] == 0)
? $\endgroup$