Language Reference
Multiplication Operator, Elementwise: #
matrix1 # matrix2;
matrix # scalar;
matrix # vector;
The elementwise multiplication operator (#) computes a new matrix with elements that are the products of the corresponding elements of matrix1 and matrix2.
For example, the following statements compute the matrix ab, shown in Figure 19:
a = {1 2,
3 4};
b = {4 8,
0 5};
ab = a#b;
print ab;
Figure 19: Results of Elementwise Multiplication
| ab | |
|---|---|
| 4 | 16 |
| 0 | 20 |
In addition to multiplying matrices that have the same dimensions, you can use the elementwise multiplication operator to multiply a matrix and a scalar.
For example, a matrix can be multiplied on either side by a
,
,
, or
matrix. The following statements multiply the
matrix
a by a column vector and a row vector. The results are shown in Figure 20.
c = {10, 100}; /* column vector */
r = {10 100}; /* row vector */
ac = a#c;
ar = a#r;
print ac, ar;
Figure 20: Elementwise Multiplication with Vectors
| ac | |
|---|---|
| 10 | 20 |
| 300 | 400 |
| ar | |
|---|---|
| 10 | 200 |
| 30 | 400 |
Elementwise multiplication is mathematically equivalent to multiplying by a diagonal matrix. However, the elementwise operation is more efficient, as shown by the following statements:
A = j(5,5,1);
v = 2:6; /* 1x5 row vector */
D = diag(v); /* 5x5 diagonal matrix */
/* multiply columns by constants */
B = A*D; /* less efficient */
B = v # A; /* more efficient */
/* multiply rows by constants */
C = D*A; /* less efficient */
C = A # v`; /* more efficient */
Elementwise multiplication is also known as the Schur or Hadamard product. Elementwise multiplication (which uses the # operator) should not be confused with matrix multiplication (which uses the * operator).
When an element of a matrix contains a missing value, the corresponding element of the product is also a missing value.
The # symbol also has a special meaning that is unrelated to multiplication. When creating lists, you can create named items by using name-value pairs. Names must be prefixed with the # symbol. For example, the syntax L = [#A=2, #"B"=3, #"A * B"=2*3] creates a list that contains three named items.