Roger Allen
Roger Allen

Reputation: 2312

matrix multiplication in core.matrix

This seems like a silly question, but I can't figure this out after a bit of looking around, so I'll ask here.

How can I multiply a 3x2 matrix by a 2x3 matrix in core.matrix? I must be misunderstanding something very basic. Naively, I expected this to work and I thought core.matrix would do the underlying math for me.

(* (matrix [[1 0 -2] 
            [0 3 -1]]) 
   (matrix [[0   3] 
            [-2 -1] 
            [0   4]]))

I found this example via first hit on a google search http://www.purplemath.com/modules/mtrxmult.htm and the expected result is

[[ 0 -5]
 [-6 -7]]

Instead, I get:

RuntimeException Incompatible shapes, cannot broadcast [3 2] to [2 3] 
clojure.core.matrix.impl.persistent-vector/eval5013/fn--5014 
(persistent_vector.clj:152)

Thanks in advance.

p.s. my namespace looks just like the example from core.matrix

(ns xyz
  (:refer-clojure :exclude [* - + == /]) ; get from core.matrix
  (:use clojure.core.matrix)
  (:use clojure.core.matrix.operators)
  (:gen-class))

Upvotes: 6

Views: 1942

Answers (1)

Alex
Alex

Reputation: 13941

The * matrix operator is an element-wise multiplication - that is, it forces the two operands to the same dimensions and produces a new matrix where the element at each position in the result is the product of the elements at that position in the operands.

I think you're looking for the mmul function from clojure.core.matrix.

Upvotes: 9

Related Questions