mikera / core.matrix

core.matrix : Multi-dimensional array programming API for Clojure
Other
701 stars 113 forks source link

Why is there no mmul! function ? #339

Closed kxygk closed 5 years ago

kxygk commented 5 years ago

in-place multiplication seems to be part of BLAS and most serious linear algebra libraries.. Is there a reason it's not included?

Could at least maybe be a wrapper for something like

(defn mmul!
  ""
  [A B]
  (assign! A (mmul A
                   B)
mikera commented 5 years ago

In general, the destination matrix for a mmul will not be the same size as the first argument. So this is not a safe function to rely on in generic code.

We could implement mmul! with a default wrapper as you suggest, but it has two problems: a) It would fail unless the argument sizes are consistent. b) It would be usually be slower than simply using the result of mmul.

There are special cases where in-place multiplication is definitely faster, e.g. mmul with a scalar array, but in such cases you would probably want to use scale! instead.

Note that there is a function set-inner-product! which probably does what you want, and is more general than the proposed mmul! (i.e. you can choose an arbitrary desination array, and it handles higher dimensional arrays correctly).

kxygk commented 5 years ago

It would fail unless the argument sizes are consistent.

I don't see the problem with that. So will a mmul if you use two matrices with non conforming dimensions

It would be usually be slower than simply using the result of mmul

The idea is that some implementations could override it and make it faster than calling mmul and then doing an extra copy

But I'm going to guess your concern is that mmul! wouldn't be valid for all the same inputs as mmul :)

There is no set-inner-product!. I think you meant add-inner-product! which does seem to do what I need. Thanks for helping me out

PS: The fact that a function called inner-product is the one I actually should be looking for to do matrix multiplication is very kinda crazy haha