On 21-05-14 15:15, Tomas Möre wrote:
Hello!
Since modern OpenGL requires some hefty matrix math I need to make a matrix math library.
Hi Tomas,
first make it correct, then you can make it fast, then you can use macros to unroll loops (assuming the compiler doesn't already do it automatically).
Below are two functions that multiply matrices, the first in the style you used, the second maybe more direct. They appear to be equally fast (slow?).
Maybe you also want to take a look at existing code, for example http://aleph0.info/scheme/matrix-bench-gambit.scm or http://docs.racket-lang.org/math/matrices.html or http://wiki.call-cc.org/eggref/4/blas or maybe a CL one. That will also allow you to compare performance and see how you're doing.
Marijn
(define (mat*~ m w dim) (define (mat*-elem i j) (let loop ((d 0) (res 0)) (cond ((< d dim) (loop (+ d 1) (+ res (* (vector-ref m (+ (* i dim) d)) (vector-ref w (+ (* d dim) j)))))) (#t res)))) (let ((res (make-vector (* dim dim) 0))) (let loop ((r 0)) (cond ((< r dim) (let lp ((c 0)) (cond ((< c dim) (vector-set! res (+ (* r dim) c) (mat*-elem r c)) (lp (+ c 1))))) (loop (+ r 1))))) res))
(define (mat* m w dim) (let ((res (make-vector (* dim dim) 0))) (let loop ((r 0)) (cond ((< r dim) (let lop ((c 0)) (cond ((< c dim) (let lp ((i 0)) (cond ((< i dim) (vector-set! res (+ (* r dim) c) (+ (vector-ref res (+ (* r dim) c)) (* (vector-ref m (+ (* r dim) i)) (vector-ref w (+ (* i dim) c))))) (lp (+ i 1))))) (lop (+ c 1))))) (loop (+ r 1))))) res))
(define m (vector 1 0 1 0 1 3 7 0 1))
(define w (vector 1 0 0 0 1 0 0 0 1))
(pp (mat*~ m w 3)) (pp (mat* m w 3))
(pp (mat*~ w m 3)) (pp (mat* w m 3))
(time (let loop ((i 10000)) (mat*~ m w 3) (if (> i 0) (loop (- i 1)))))
(time (let loop ((i 10000)) (mat* m w 3) (if (> i 0) (loop (- i 1)))))