mikera / core.matrix

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

Matrix element wise multiplication by column vector #353

Open zbouslikhin opened 2 years ago

zbouslikhin commented 2 years ago

Hello,

First of all, many thanks for the amazing library! I'm sorry if I'm asking such a basic question however, my background is from Matlab.

I'm trying to simply perform an element wise multiplication operation between a 3x3 matrix and a column vector (or in other words, a 3x1 matrix). In Matlab, I'd do the following:

mat3_3 = [1 0 1; 0 1 1; 1 1 0];
mat3_1 = [0 1 2]';
result = mat3_3 .* mat3_1; % => returns
                                                                    %  0     0     0
                                                                    %  0     1     1
                                                                    %  2     2     0

In Clojure, using core.matrix, I tried the following, but no success:

(m/mul (m/matrix [[0] [1] [2]]) (m/matrix [[1 0 1] [0 1 1] [1 1 0]]) )
mikera commented 2 years ago

The automatic broadcasting in core.matrix is based on adding leading dimensions. i.e. a shape of [3] can broadcast to [1 3] but not [3 1] by default. It does this by copying across the newly added dimensions, so your [0 1 2] vector will broadcast to [[0 1 2] [0 1 2] [0 1 2]] but not [[0 0 0] [1 1 1] [2 2 2]]

Given this, I suggest transposing the [3 3] matrix, multiplying by the vector then transposing back.