8
$\begingroup$

I know that matrices product is correct when the number of the columns of the first matrix is equal to the number of rows of the second matrix.

Why I can't do the product between a column vector and a row vector in Mathematica? For example:

$$\begin{bmatrix}1 \\ 2 \\ 3 \end{bmatrix} \, \begin{bmatrix}1 & 2 & 3\end{bmatrix}$$

Mathematica gives me the error: Dot::dotsh: Tensors {{1},{2},{3}} and {1,2,3} have incompatible shapes.

Thank you so much.

$\endgroup$
2
  • 6
    $\begingroup$ Try {{1}, {2}, {3}}.{{1, 2, 3}} $\endgroup$
    – Coolwater
    Commented Dec 15, 2017 at 10:01
  • $\begingroup$ Thank you very much @Coolwater $\endgroup$ Commented Dec 15, 2017 at 10:04

2 Answers 2

6
$\begingroup$

Remember that Mathematica does not distinguish between row vectors and column vectors: all vectors are seen as lists (tutorial). You could convert each vector into a $1\times n$ matrix (row vector) and a $n\times1$ matrix (column vector), as @Mefitico suggests, and then matrix-multiply, Matlab-style. You could also stay with vectors-as-lists and do an outer product:

Outer[Times, {1, 2, 3}, {1, 2, 3}]

or

KroneckerProduct[{1, 2, 3}, {1, 2, 3}]
$\endgroup$
0
3
$\begingroup$

I suggest you define a function to perform such products like:

VecProd[v__, u__] := Transpose[{u}].{v}

Then for your case:

VecProd[{1, 2, 3}, {1, 2, 3}]

Evaluates to:

{{1, 2, 3}, {2, 4, 6}, {3, 6, 9}}

This looks simple, but as a non frequent user, it becomes annoying to wrap my head around this particularity every time.

$\endgroup$
4
  • $\begingroup$ Your matching pattern seems off. I think it should be VecProd[v_, u_] := ... (or VecProd[v_List, u_List] := ... for clarity) since you'd never want this to match for more than 2 arguments. $\endgroup$ Commented Feb 27, 2019 at 12:03
  • $\begingroup$ @SjoerdSmit : Not sure if I understood your comment. I use double underscore characters because u and v are vectors with variable size, as opposed to a scalar but looking at Wolfram Doccumentation it seems unclear if that was necessary. $\endgroup$
    – Mefitico
    Commented Feb 27, 2019 at 16:12
  • 1
    $\begingroup$ The pattern v__ will not match a vector of variable size; it will match a sequence of arguments. For example, VecProd[1,2,3,4,5,6] will also match the pattern and give nonsense results. In that case, it matches v to 1 and u to Sequence[2,3,4,5,6]. A variable-length vector named u should be matched as u : {__} (list with 1 or more elements) or simply u_List (anything with the head List). $\endgroup$ Commented Feb 27, 2019 at 16:41
  • $\begingroup$ @SjoerdSmit : Thanks for the comment, I"ll check this later and update the answer. $\endgroup$
    – Mefitico
    Commented Feb 27, 2019 at 17:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.