views:

159

answers:

1

I am trying to add a matrix and it is not working...

(define (matrix-matrix-add a b)
  (map (lambda (row) (row-matrix-add row b))
       a))

(define (row-matrix-add row matrix)
  (if (null? (car matrix))
      '()
      (cons (add-m row (map car matrix))
            (row-matrix-add row (map cdr matrix)))))

(define (add-m row col)
  (if (null? col)
      0
      (+ (car row)
         (car col)
         (add-m (cdr row) (cdr col)))))
+1  A: 

Here is a working implementation:

(define (matrix-add m1 m2)

  (define (matrix-add-row r1 r2 res-row)
    (if (and (not (null? r1)) (not (null? r2)))
    (matrix-add-row (cdr r1) (cdr r2)
            (cons (+ (car r1) (car r2)) res-row))
    (reverse res-row)))

  (define (matrix-add-each m1 m2 res)
    (if (and (not (null? m1)) (not (null? m2)))
    (let ((res-row (matrix-add-row (car m1) (car m2) ())))
      (matrix-add-each (cdr m1) (cdr m2) (cons res-row res)))
    (reverse res)))
  (matrix-add-each m1 m2 ()))

Sample usage and output:

>  (matrix-add '((7 2) (3 8)) '((4 8) (0 5)))
((11 10) (3 13))
> (matrix-add '((5 2) (4 9) (10 -3)) '((-11 0) (7 1) (-6 -8)))
((-6 2) (11 10) (4 -11))
Vijay Mathew