logo

Multiplying Matrices Row-wise and Column-wise with Scalar in Julia 📂Julia

Multiplying Matrices Row-wise and Column-wise with Scalar in Julia

Overview

Introducing how to perform scalar multiplication by row and column on matrices in Julia.

Code

julia> d = 1:10
1:10

julia> X = ones(Int64, 10, 10)
10×10 Matrix{Int64}:
 1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1  1  1  1  1

Given a vector d and a unity matrix X, scalar multiplication by row or column can be performed through broadcasting the multiplication *. It doesn’t matter whether you multiply from the left or the right, but whether the vector is vertically or horizontally long determines the row/column.

Scalar multiplication per row X .* d

For scalar multiplication per row, a vertically long vector, i.e., $d \in \mathbb{R}^{n \times 1} \approx \mathbb{R}^{n}$, is needed.

julia> X .* d
10×10 Matrix{Int64}:
  1   1   1   1   1   1   1   1   1   1
  2   2   2   2   2   2   2   2   2   2
  3   3   3   3   3   3   3   3   3   3
  4   4   4   4   4   4   4   4   4   4
  5   5   5   5   5   5   5   5   5   5
  6   6   6   6   6   6   6   6   6   6
  7   7   7   7   7   7   7   7   7   7
  8   8   8   8   8   8   8   8   8   8
  9   9   9   9   9   9   9   9   9   9
 10  10  10  10  10  10  10  10  10  10

julia> d .* X
10×10 Matrix{Int64}:
  1   1   1   1   1   1   1   1   1   1
  2   2   2   2   2   2   2   2   2   2
  3   3   3   3   3   3   3   3   3   3
  4   4   4   4   4   4   4   4   4   4
  5   5   5   5   5   5   5   5   5   5
  6   6   6   6   6   6   6   6   6   6
  7   7   7   7   7   7   7   7   7   7
  8   8   8   8   8   8   8   8   8   8
  9   9   9   9   9   9   9   9   9   9
 10  10  10  10  10  10  10  10  10  10

Scalar multiplication per column X .* d'

For scalar multiplication per column, a horizontally long vector, i.e., $d \in \mathbb{R}^{1 \times n} $, is needed.

julia> X .* d'
10×10 Matrix{Int64}:
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10

julia> d' .* X
10×10 Matrix{Int64}:
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  5  6  7  8  9  10

Complete Code

d = 1:10
X = ones(Int64, 10, 10)

X .* d
d .* X

X .* d'
d' .* X

Environment

  • OS: Windows
  • julia: v1.9.0