2
$\begingroup$

I have the following table:

n = 3;

myTab = Flatten[Table[{i, j}, {i, -1, n}, {j, -1, n}], 1]

(*output:
{{-1,-1},{-1,0},{-1,1},{-1,2},{-1,3},{0,-1},{0,0},{0,1},{0,2},{0,3},
{1,-1},{1,0},{1,1},{1,2},{1,3},{2,-1},{2,0},{2,1},{2,2},{2,3},{3,-1},
{3,0},{3,1},{3,2},{3,3}}
*)

Now from myTab, I only want to select those elements {i,j} that matches the pattern {i,i+1} or {n,i}. What is the best way to achieve that in Mathematica? Any help is much appreciated!

$\endgroup$

2 Answers 2

5
$\begingroup$

Using patterns and Cases:

Cases[myTab, ({i_ ,j_} /; j == i + 1) | {n, _}]
Cases[myTab,  {i_, j_} /; j == i + 1 || i == n]

(* Out:
{{-1, 0}, {0, 1}, {1, 2}, {2, 3},
 {3, -1}, { 3, 0}, {3, 1}, {3, 2}, {3, 3}} *)

Using Select with a selector function:

Select[myTab, Last[#] == First[#] + 1 || First[#] == n &]

(* Same output *)

In case it helps, note also that your myTab can be generated directly with Tuples:

myTab == Tuples[Range[-1, n], 2]
(* True *)
$\endgroup$
5
  • $\begingroup$ This is a great answer, thanks @MarcoB $\endgroup$
    – TDH
    Jun 21, 2022 at 11:47
  • $\begingroup$ @TDH Glad it helped! $\endgroup$
    – MarcoB
    Jun 21, 2022 at 11:52
  • $\begingroup$ The Tuples code is very nice, thanks @MarcoB! $\endgroup$
    – TDH
    Jun 21, 2022 at 12:39
  • 1
    $\begingroup$ Came to the same solution: Cases[myTab, {a_, b_} /; a + 1 == b || b == n] $\endgroup$
    – Valacar
    Jun 21, 2022 at 13:46
  • 1
    $\begingroup$ @Valacar Great minds think alike :-) $\endgroup$
    – MarcoB
    Jun 21, 2022 at 13:47
2
$\begingroup$
n = 3;
run = n - (-1) + 1; 
sel = Flatten@
   Normal@SparseArray[{Band[{1, 2}] -> 1, {run, _} -> 1}, {run, run}];
res = Pick[myTab, sel, 1]

{{-1, 0}, {0, 1}, {1, 2}, {2, 3}, {3, -1}, {3, 0}, {3, 1}, {3, 2}, {3, 3}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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