# Skipping over iterator values in a Table

I have been using the built-in function Table for some computations. (The following is not an actual representation of the equations I am using).

$$\text{Table}[f[k]=g[k],\{k,1,10\}]$$

However, the assignment $f[k]=g[k]$ is not true for one $k$ value, say $k=6$. That is, say, $g[k]=k^2+1$ for $k\neq 6$ and $g=1$ (when $k=6$).

I can then break the table into two parts: $\{k,1,5\}$ and $\{k,7,10\}$.

Is there any other (more efficient) way of doing this?

• Please do not use LaTeX to format code. It makes it impossible to copy and paste it. Use a proper code box. – Szabolcs Aug 10 '14 at 15:05

You can do this without Table:

g[k_] := k^2 + 1

Map[If[# != 6, f[#] = g[#], f[#] = 1] &, Range]


{2, 5, 10, 17, 26, 1, 50, 65, 82, 101}

You can also use Scan in place of Map (it may be slightly faster for large lists). Note that no result will be displayed, but f will still retain the values stored in it.

Scan[If[# != 6, f[#] = g[#], f[#] = 1] &, Range]


You can retrieve the values as follows:

f /@ Range


{2, 5, 10, 17, 26, 1, 50, 65, 82, 101}

• Dear @RunnyKine, Thanks for your help. – Radz Aug 10 '14 at 5:26
• @Radz You're welcome. Glad I could help. – RunnyKine Aug 10 '14 at 5:27

In addition to RunnyKine's recommendation of If here are two other methods to consider.

### 1: Unset or restore the value

Simply Unset f afterward:

Do[f[k] = g[k], {k, 10}];
f =.

Array[f, 10]

{g, g, g, g, g, f, g, g, g, g}


Note f is returned as it is undefined.

Or if f already has a value save and restore it:

f[k_] := 9 k

k6 = f;
Do[f[k] = g[k], {k, 10}];
f = k6;

Array[f, 10]

 {g, g, g, g, g, 54, g, g, g, g}


### 2: Delete the value from your iterator range

Do[f[k] = g[k], {k, Range ~Delete~ 6}];

Array[f, 10]

{g, g, g, g, g, f, g, g, g, g}


Again note f is returned in the output.

• Dear @Mr.Wizard, Thank you for you help. – Radz Aug 11 '14 at 2:03

Of course you can use the If also inside the table:

Table[If[k != 6, f[k] = g[k], f[k] = 1], {k, 10}]


You can also use the If on the right hand side of the assignment:

Table[f[k] = If[k != 6, g[k], 1], {k, 10}]


If the whole purpose of the table is the assignment, that is you are not really interested in the list it outputs, you can replace Table with Do (I imagine that would also be faster, but I haven't measured it):

Do[If[k != 6, f[k] = g[k], f[k] = 1], {k, 10}]


Another option (which especially is useful if the two ranges are far apart and you don't need to assign to intermediate values of f) is to build the iterator from the two subranges explicitly:

Do[f[k] = g[k], {k, Range ~Join~ Range[7,10]}]


Yet another option would be to use Piecewise:

Table[f[k]=Piecewise[{{g[k], k!=6}}, 1], {k, 10}]

• Dear @celtschk, Thank you for you help. – Radz Aug 11 '14 at 2:04
• @Radz: You're welcome. – celtschk Aug 13 '14 at 8:08