Multiply rows of matrix by vector?
I think you're looking for sweep()
.
# Create example data and vector
mat <- matrix(rep(1:3,each=5),nrow=3,ncol=5,byrow=TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 2 2 2 2 2
[3,] 3 3 3 3 3
vec <- 1:5
# Use sweep to apply the vector with the multiply (`*`) function
# across columns (See ?apply for an explanation of MARGIN)
sweep(mat, MARGIN=2, vec, `*`)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 4 6 8 10
[3,] 3 6 9 12 15
It's been one of R's core functions, though improvements have been made on it over the years.
Multiply rows of matrix by vector elementwise in pytorch?
The answer was so trivial that I overlooked it.
For simplicity I used a smaller vector and matrix in this answer.
Multiply rows of matrix by vector:
X = torch.tensor([[1,2,3],[5,6,7]])
y = torch.tensor([7,4])
X.transpose(0,1)*y
# or alternatively
y*X.transpose(0,1)
output:
tensor([[ 7, 20],
[14, 24],
[21, 28]])
tensor([[ 7, 20],
[14, 24],
[21, 28]])
Multiply columns of matrix by vector:
To multiply the columns of matrix by a vector you can use the same operator '*' but without the need to transpose the matrix (or vector) first
X = torch.tensor([[3, 5],[5, 5],[1, 0]])
y = torch.tensor([7,4])
X*y
# or alternatively
y*X
output:
tensor([[21, 20],
[35, 20],
[ 7, 0]])
tensor([[21, 20],
[35, 20],
[ 7, 0]])
Nice way to multiply each row of a matrix by a vector in r
I think this is what you are looking for...
t( t(mat) * vec )
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 2 3 4
*
like most other operators in R is vectorised. The t
is necessary because R will recycle column-wise. The apply
solution is:
t( apply( mat , 1 , `*` , vec ) )
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 2 3 4
Multiply matrix rows by element row of vector
If you express your vector as a vector, rather than as a matrix, it works:
m <- matrix(c(0,1,2,3), nrow = 2)
v <- matrix(c(0, 6), nrow = 2)
> m*as.vector(v)
[,1] [,2]
[1,] 0 0
[2,] 6 18
Or, call it as a vector from the start:
m <- matrix(c(0,1,2,3), nrow = 2)
v <- c(0,6)
> m*v
[,1] [,2]
[1,] 0 0
[2,] 6 18
Vector matrix element wise multiplication (by rows) in Julia, efficiently
You have at least the following options:
(v.*A')'
(OP's suggestion)v'.*A
(shortest way)mapslices(row->v.*row, A, 2)
- Manual implementation from @AborAmmar's post (fastest way)
i.e.
function tt(v, A)
r = similar(A)
@inbounds for j = 1:size(A,2)
@simd for i = 1:size(A,1)
r[i,j] = v[j] * A[i,j] # fixed a typo here!
end
end
r
end
Speed comparison (in ascending order)
julia> @btime tt($v,$A); # @AborAmmar's answer
38.826 ns (1 allocation: 112 bytes)
julia> @btime ($v)'.*$A;
49.920 ns (1 allocation: 112 bytes)
julia> @btime (($v).*($A)')';
123.797 ns (3 allocations: 336 bytes)
julia> @btime mapslices(row->($v).*row, $A, 2);
25.174 μs (106 allocations: 5.16 KiB)
EDIT: Took more careful and faster manual implementation from @AborAmmar's post (replaced old one) and updated speed comparison.
How to multiply each row in matrix by its scalar in NumPy?
You can use broadcasting: A * B[:, None]
:
array([[ 1, 2, 3],
[ 8, 10, 12],
[21, 24, 27]])
R - Multiply every row of df or matrix with a vector
Option#1: Using data.table
features:
Note:it works because column number and value matches for a
a[,lapply(.SD,function(x)(x*b[,x]))]
# V1 V2 V3 V4
#1: 2 4 6 8
#2: 2 4 6 8
#3: 2 4 6 8
Option#2: could be:
t(t(b) * (as.matrix(a)[1,]))
[,1] [,2] [,3] [,4]
[1,] 2 4 6 8
[2,] 2 4 6 8
[3,] 2 4 6 8
UPDATE
Option#3: To handle decimal/actual values in a
#Cases when `a` contains decimal values can be handled as
a <- data.table(t(c(1, 0.24, 3, 4)))
b <- matrix(data=2, nrow=3, ncol=4)
a[,lapply(V1:V4,function(i)(a[[i]]*b[,i]))]
# V1 V2 V3 V4
#1: 2 0.48 6 8
#2: 2 0.48 6 8
#3: 2 0.48 6 8
element wise multiplication vector with rows of matrix
I assume you're using numpy. You can use matrix *= vector.reshape(-1, 1)
. This will convert the vector to a column, then multiply the rows.
Related Topics
Simpler Population Pyramid in Ggplot2
Construct a Manual Legend For a Complicated Plot
Unlist Data Frame Column Preserving Information from Other Column
R Shiny Passing Reactive to Selectinput Choices
Gradient of N Colors Ranging from Color 1 and Color 2
Increase Distance Between Text and Title on the Y-Axis
Sample N Random Rows Per Group in a Dataframe
How to Extract a Single Column from a Data.Frame as a Data.Frame
Summarizing Multiple Columns With Data.Table
Change the Blank Cells to "Na"
Efficient Way to Rbind Data.Frames With Different Columns
Remove Columns from Dataframe Where All Values Are Na
All Levels of a Factor in a Model Matrix in R
Use a Value from the Previous Row in an R Data.Table Calculation