lua-users home
lua-l archive

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


Hi guys,

I decided to tackle a little bit with a multidimensional matrix
representation in lua, and I came up with a nice solution (I guess :)).
The simplest way I found to allow correct indexing was to build a
struct with a pointer to Udata (from lobject.h) and to provide a small
extension to the API so that full userdatas could be pushed to the
virtual stack. I know it's a bit overkill, but it worked like a charm.
:)

I tried to make an implementation as general as possible, allowing for
multidimensional operations (sums and multiplications). Some examples:

> require 'Matrix'
> M = Matrix:new(3, 3) -- 3 x 3 matrix
> M:fill(1)
> N = Matrix:identity(3)
> X = M * N
> = X
matrix<dim: 2, size: 3>: 0x80a19e8
> = M
matrix<dim: 2, size: 3>: 0x80a0530
> = X == M
true
> L = M:copy()
> for i = 1, 3 do for j = 1, 3 do L[i][j] = i*j end end
> X = M + L
> for i = 1, 3 do for j = 1, 3 do print(i,j,X[i][j]) end end
1       1       2
1       2       3
1       3       4
2       1       3
2       2       5
2       3       7
3       1       4
3       2       7
3       3       10

You can see all available routines by issuing table.foreach(Matrix,
print). I implemented just the very basic routines, and I believe that
more powerful methods (inverse, LU decomposition, determinants) can be
obtained through a nice interface with LAPACK/BLAS. Should more people
show interest, I can try to do that. But be warned though: I am very,
very green in Lua and C. :)

Please check (and test!) the code -- mainly for robustness and soundness
since I'm not sure about my GC routine -- that can be found at:

http://www.dam.brown.edu/people/carvalho/luamatrix.tar.gz

Note that lua-5.0.1 sources are needed; modify the Makefile for their
location. Needless to say, critics and opinions are more than welcome!
:)

Cheers,
Luis.

-- 
Mathematicians practice absolute freedom.
                -- Henry Adams

-- 
Luis Carvalho
Applied Math PhD Student - Brown University
PGP Key: E820854A <carvalho@dam.brown.edu>

Attachment: pgpX1eRYRUDcN.pgp
Description: PGP signature