Search code examples
clojurematrix-multiplication

Clojure matrix multiplication error: "Mismatched vector sizes" (clojure.core.matrix)


I have a matrix of size [1, 10] and another of size [1, 50] (they are both vectors - one will be transposed) which I want to multiply. I can do this in MATLAB but the Clojure library I am using returns an error indicating that the vector shapes are mismatched.

Here is the Clojure code (fails)

(def A [-0.4300 0.8205 0.3060 0.7011 0.3717 0.3790 0.6332 0.6179 0.5414 0.7277])
(m/shape A)
(def B [1 4.5239 1.0 4.54133 4.17334 1.0 2.3195 1.25481 2.57760 0.999 1.71030 1.167121 0.996 1.0 1.0 1.0 1.0 2.42060 4.53421 1.0 3.81672 2.26177 1.412147 1.13449 4.22844 1.87670 1.42931 4.13310 1.0 3.06024 1.0 0.999 1.02989 8.92018 8.90729 6.60117 2.61610 7.31420 1.0 4.23987 0.999 1.05592 5.31238 1.0 1.0 0.999 7.97549 1.6177 1.0 1.0])
(m/shape B)
(m/mmul (m/transpose A) B)

Equivalent operation in MATLAB:

A = [-0.4300 0.8205 0.3060 0.7011 0.3717 0.3790 0.6332 0.6179 0.5414 0.7277];
size(A)
B = [1 4.5239 1.0 4.54133 4.17334 1.0 2.3195 1.25481 2.57760 0.999 1.71030 1.167121 0.996 1.0 1.0 1.0 1.0 2.42060 4.53421 1.0 3.81672 2.26177 1.412147 1.13449 4.22844 1.87670 1.42931 4.13310 1.0 3.06024 1.0 0.999 1.02989 8.92018 8.90729 6.60117 2.61610 7.31420 1.0 4.23987 0.999 1.05592 5.31238 1.0 1.0 0.999 7.97549 1.6177 1.0 1.0];
size(B)
C = A' * B;
size(C)

Clearly the operation is mathematically possible - it should return a [10, 50] matrix... is there an error in the way I've implemented the calculation or is this a bug?


Solution

  • According to mmul documentation, the transposition is implicit in a vector depending on argument position:

    Performs matrix multiplication on matrices or vectors. Equivalent to inner-product when applied to vectors. Will treat a 1D vector roughly as a 1xN matrix (row vector) when it's the first argument, or as an Nx1 matrix (column vector) when it's the second argument--except that the dimensionality of the result will be different from what it would be with matrix arguments.

    So, you should not transpose yourself.