lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I'm a novice trying to generate factorial table expansion as described below. I
am able to do this with many nested for loops, but I seem unable to do this in
the proper spirit of lua table and iteration techniques (e.g. the permutations
generater in PiL 9.1). 

The idea is to turn a table of tables like this:

factors={
	side     = { left = -1, right = 1 },
	duration = { short = 200, med = 500, long = 800 },
	validity = { valid = 1, invalid = 0 }
}

into a table containing one table for every possible combination of factor
levels, for the above example a table of 2*3*2 entries:

conditions = {
	{ left, short, valid },
	{ left, short, invalid },
	{ left, med, valid },
	{ left, med, invalid },
	{ left, long, valid },
	{ left, long, invalid },
	{ right, short, valid },
	{ right, short, invalid },
	{ right, med, valid },
	{ right, med, invalid },
	{ right, long, valid },
	{ right, long, invalid },
}


My code below should illustrate what I mean about not being in the spirit of
lua! I'd very much appreciate ideas about how to improve this novice effort!
Rob

-----

function icount(t)
 local k, v
 local i = 0
 for k, v in pairs(t) do
  if v then
   i = i+1
  end
 end
 return i
end

function createdesign(design, repsPerBlock, nblocks)
 local repsPerBlock = repsPerBlock or 1
 local nblocks = nblocks or 1
 local nconds = 1
 local nlvls = {}
 local conds = {}
 local nfactor = icount(design)
 for f,lvls in pairs(design) do
  if lvls then
   nlvls[f] = icount(lvls)
   nconds = nconds * nlvls[f]
  end
 end
 
 blocksize = nconds*repsPerBlock
 ntrials = blocksize * nblocks
 for i = 1, ntrials do
  conds[i] = {}
 end

 ncycles = 1
 for f, lvls in pairs(design) do 
  nlevels = icount(lvls)
  trlsPerCyc = blocksize/ncycles
  nreps = trlsPerCyc/nlevels
  trialsthisblock = 0
  while( trialsthisblock < blocksize) do
   for cycle = 1, ncycles do
    for level in pairs(lvls) do
     for rep = 1, nreps do
      for block = 1, nblocks do
       trialno = (block-1)*blocksize + trialsthisblock+1
       value = level
       print(trialno,value)
       conds[trialno][f] = value
      end -- block
      trialsthisblock = trialsthisblock+1
     end -- rep
    end -- level
   end -- cycle
   ncycles = ncycles * nlevels
  end -- trialsthisblock
 end -- factor
        
 return conds
end



--
This mail sent through http://webmail.bangor.ac.uk