       Re: nested list creation with index skipping

• To: mathgroup at smc.vnet.net
• Subject: [mg73965] Re: nested list creation with index skipping
• From: "Ray Koopman" <koopman at sfu.ca>
• Date: Sat, 3 Mar 2007 03:57:44 -0500 (EST)
• References: <esb4kb\$3sr\$1@smc.vnet.net>

```J=E1nos wrote:
> Hi,
>
> What is the most economical way to create a nested list where
> during the creation I have to jump over some index values?

That will depend on how many elements you want to skip and how
expensive they are to generate. If they're cheap and you want to skip
only a few, then generate the entire array and delete the unwanted
elements. But if they're expensive and you want to skip many, then
selective generation will be more economical.

>
> For a simple example
> n=10;
> tbl=Table[Table[j,{j,1,n}],{i,1,n}]
>
> Here I would like to skip any index where i==j.

For this simple case I would generate & delete:

Delete[Range@n,#]& /@ Range@n

>                                                 Table does
> not give me the option Assuming[ i=!=j] or something similar.
> Of course I can drop later on those elements where i==j,
> but that is additional processing and not economical, like:
>
> Table[Select[tbl[[i]], #1 =!= i & ], {i, 1, n}]
>
> The best I can do as a newbie, is to have Reap-Sow cycle
> where I do NOT collect values for i==j, like:
>
> lst = First[Last[Reap[i = 1; While[i <= n,
>         rj = First[Last[Reap[j = 1; While[j <= n,
>                If[j =!= i, Sow[j], Null]; j++; ]; ]]];
>          Sow[rj]; i++; ]; ]]]

You may also want to consider the clarity of the code ;)

>
> In general, I can have two lists for example:
> iis={1,2,5,6,8,9}
> jjs={2,3,5,7,8}
> Where the values in these lists indicate what index values
> I want to take into account when I create the list.
>
> With the Reap-Sow cycle it can be done this way:
>
> lst = First[Last[Reap[i = 1; While[i <= n,
>         rj = First[Last[Reap[j = 1; While[j <= n,
>                If[j =!= i && MemberQ[jjs, j], Sow[j],
>                  Null]; j++; ]; ]]]; If[MemberQ[iis, i],
>           Sow[rj], Null]; i++; ]; ]]]

Does this do what you want?

DeleteCases[jjs,#]& /@ iis

>
> I guess it leads to SparseArray sooner or later, but I do
> not want 0 for unspecified elements like SparseArray does.
>