4

I am trying to create a table with conditionals inline. For example, I'd like to create a 2 dimensional table like this:

Table[{i, j} -> 1, {i, 1, 3}, {j, 1, 3}]

Now, I'd like Table to generate values only if i != 1. It should be easy, but I'm lost. I've tried several approaches, like the following, but I don't get what I want in a neat way:

Table[If[i != 1, {i, j} -> 1], {i, 1, 3}, {j, 1, 3}]

{{Null, Null, Null}, {{2, 1} -> 1, {2, 2} -> 1, {2, 3} -> 1}, {{3, 1} -> 1, {3, 2} -> 1, {3, 3} -> 1}}

I know, I could delete cases, but there must be a clean and simple way!

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
senseiwa
  • 515
  • 2
  • 7

1 Answers1

3

To my mind, it would be better to control the values i is allowed take in the second argument to Table rather than in the first. For your particular example that means writing the very simple and efficient

Table[{i, j} -> 1, {i, 2, 3}, {j, 1, 3}]

{{{2, 1} -> 1, {2, 2} -> 1, {2, 3} -> 1},
{{3, 1} -> 1, {3, 2} -> 1, {3, 3} -> 1}}

This approach can be quit general. For example

Table[{i, j} -> 1, {i, #^2 & /@ Range[5]}, {j, 1, 3}]

{{{1, 1} -> 1, {1, 2} -> 1, {1, 3} -> 1},
{{4, 1} -> 1, {4, 2} -> 1, {4, 3} -> 1},
{{9, 1} -> 1, {9, 2} -> 1, {9, 3} -> 1},
{{16, 1} -> 1, {16, 2} -> 1, {16, 3} -> 1},
{{25, 1} -> 1}, {25, 2} -> 1, {25, 3} -> 1}}

Edit

Adding this to cover the case raised in senseiwa's comment:

I am not sure how I can use your solution for, say, i != K, given a K > 0.

There are many possibilities. Here is one.

With[{k = 4}, Table[{i, j} -> 1, {i, Delete[Range[5], k]}, {j, 1, 3}]]

{{{1, 1} -> 1, {1, 2} -> 1, {1, 3} -> 1},
{{2, 1} -> 1, {2, 2} -> 1, {2, 3} -> 1},
{{3, 1} -> 1, {3, 2} -> 1, {3, 3} -> 1},
{{5, 1} -> 1, {5, 2} -> 1, {5, 3} -> 1}}

Perhaps I should remark that the index specifier for i (or any index) in a Table expression can be a list specifying the exactly those indexes that i should obtain. By creating such a list, either within the Table expression (as I have done here) or external to it, it possible to select any subset of an index range.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257