Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matrix multiplication in core.matrix

Tags:

matrix

clojure

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))
like image 833
Roger Allen Avatar asked Nov 14 '13 16:11

Roger Allen


People also ask

Can you multiply a 2x3 matrix with a 2x2 matrix?

For example, the 2 × 2 and 2 × 3 matrices of multiplication are possible and the resultant matrix is a 2 × 3 matrix.

Can you multiply matrix with matrix?

To multiply a matrix with another matrix, we have to think of each row and column as a n-tuple. Each entry will be the dot product of the corresponding row of the first matrix and corresponding column of the second matrix.


1 Answers

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.

like image 124
Alex Avatar answered Sep 22 '22 12:09

Alex