Element-wise operations

From Rosetta Code
Revision as of 15:23, 8 June 2011 by Avi (talk | contribs) (Added task, Common Lisp implementation.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Element-wise operations
You are encouraged to solve this task according to the task description, using any language you may know.

Similar to Matrix multiplication and Matrix transposition, the task is to implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement addition, subtraction, multiplication, division and exponentiation.

Extend the task if necessary to include additional basic operations, which should not require their own specialised task. A reference implementation in Common Lisp is included.

Common Lisp

Element-wise matrix-matrix operations. Matrices are represented as 2D-arrays. <lang lisp>(defun element-wise-matrix (fn A B)

 (let* ((len (array-total-size A))
        (m   (car (array-dimensions A)))
        (n   (cadr (array-dimensions A)))
        (C   (make-array `(,m ,n) :initial-element 0.0d0)))
   
   (loop for i from 0 to (1- len) do
        (setf (row-major-aref C i) 
              (funcall fn
                       (row-major-aref A i)
                       (row-major-aref B i))))
   C))
A.+B, A.-B, A.*B, A./B, A.^B.

(defun m+ (A B) (element-wise-matrix #'+ A B)) (defun m- (A B) (element-wise-matrix #'- A B)) (defun m* (A B) (element-wise-matrix #'* A B)) (defun m/ (A B) (element-wise-matrix #'/ A B)) (defun m^ (A B) (element-wise-matrix #'expt A B))</lang>

Elementwise scalar-matrix operations. <lang lisp> (defun element-wise-scalar (fn A c)

 (let* ((len (array-total-size A))
        (m   (car (array-dimensions A)))
        (n   (cadr (array-dimensions A)))
        (B   (make-array `(,m ,n) :initial-element 0.0d0)))
   
   (loop for i from 0 to (1- len) do
        (setf (row-major-aref B i) 
              (funcall fn
                       (row-major-aref A i)
                       c)))
   B))
c.+A, A.-c, c.*A, A./c, A.^c.

(defun .+ (c A) (element-wise-scalar #'+ A c)) (defun .- (A c) (element-wise-scalar #'- A c)) (defun .* (c A) (element-wise-scalar #'* A c)) (defun ./ (A c) (element-wise-scalar #'/ A c)) (defun .^ (A c) (element-wise-scalar #'expt A c)) </lang>