1

I would like to define a procedure or function that takes as input an integer, s, and gives as output two nested lists. I have written code (shown below) that does this for one particular value of s, but I don't know how to generalize it. I would like to be able to get the nested lists for different input values without having to define and re-define s. Any help or suggestions would be much appreciated!

    s = 4;
    popIndicies = Range[s^2];
    list = Table[Table[Partition[popIndicies, s], {3}], {3}];
    test = list;
    output = {};
    Do[temp2 = {};
      Do[
       temp1 = {};
       Do[
        temp0 = {};
Do[AppendTo[temp0, test[[l, i, k, j]]], {j, s}];
AppendTo[temp1, temp0], {i, 3}];
       row = Flatten[temp1];
       AppendTo[temp2, row], {k, s}];
      AppendTo[output, temp2], {l, 3}];
    output = Flatten[output, 1];
    Partition[output, s*3];
    latticeWthPadding = {};
    Do[AppendTo[latticeWthPadding, output[[s + i, s ;; 2*s + 1]]], {i, 0, 
       s + 1}];
    neighborhoods = {};
    Do[
     Do[AppendTo[
       neighborhoods, {latticeWthPadding[[i, j]], 
        latticeWthPadding[[i, j - 1]], latticeWthPadding[[i, j + 1]], 
        latticeWthPadding[[i - 1, j]], 
        latticeWthPadding[[i + 1, j]]}], {j, 2, s + 1}], {i, 2, s + 1}]
    latticeWthPadding // TableForm
    neighborhoods // TableForm
debShel
  • 13
  • 1
  • 4

2 Answers2

3

The following does (I believe) the same as your code. Perhaps I could do it better if I understood what are you trying to calculate

calc[s_Integer] := 
 Module[{output, latticeWthPadding, neighborhoods}, 
  output = ArrayFlatten[ Array[1 &, {3, 3}] /. 1 -> Partition[Range[s^2], s]];
  latticeWthPadding = (output[[s + #, s ;; 2*s + 1]]) & /@  Range[0, s + 1];
  neighborhoods = Flatten[Table[Flatten[{Permute[ #[[2]], Cycles[{{1, 2}}]], #[[1, 2]], #[[3, 2]]}]&@
      (latticeWthPadding[[i ;; i + 2, j ;; j + 2]] CrossMatrix[1]), {i, 1, s}, {j, 1, s}], 1];
  {latticeWthPadding, neighborhoods}]

{latticeWthPadding, neighborhoods} = calc[5]
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
0

You must define a function and use Module[], something like this:

functionName[s_]:=Module[{localVariable1, ...}, sentence1; sentence2; ..... sentencen ]

Read more in the documentation center.

user19604
  • 71
  • 1