add a vector to all rows of a matrix
We can use col
to replicate the 'a' elements
b + a[col(b)]
# [,1] [,2] [,3] [,4] [,5]
#[1,] 2 3 1 1 1
#[2,] 2 3 1 1 1
#[3,] 2 3 1 1 1
#[4,] 2 3 1 1 1
#[5,] 2 3 1 1 1
#[6,] 2 3 1 1 1
Or a faster option would be to use rep
b + rep(a, each = nrow(b))
Or use sweep
sweep(b, 2, a, "+")
Benchmarks
set.seed(24)
b <- matrix(sample(0:9, 8000*5000, replace=TRUE), ncol=5000)
a <- sample(0:3, 5000, replace=TRUE)
system.time(b + a[col(b)])
# user system elapsed
# 1.08 0.06 1.14
system.time(b + rep(a, each = nrow(b)))
# user system elapsed
# 0.83 0.03 0.86
system.time(t(a+t(b)))
# user system elapsed
# 1.14 0.03 1.17
system.time(sweep(b, 2, a, "+"))
# user system elapsed
# 0.62 0.06 0.69
Adding a vector to matrix rows in numpy
For adding a 1d array to every row, broadcasting already takes care of things for you:
mat += vec
However more generally you can use np.newaxis
to coerce the array into a broadcastable form. For example:
mat + np.ones(3)[np.newaxis,:]
While not necessary for adding the array to every row, this is necessary to do the same for column-wise addition:
mat + np.ones(5)[:,np.newaxis]
EDIT: as Sebastian mentions, for row addition, mat + vec
already handles the broadcasting correctly. It is also faster than using np.newaxis
. I've edited my original answer to make this clear.
How to assign the same vector in every row of a matrix
You could use replicate
to copy directly, without needing to start with an empty matrix
vec <- 1:5
t(replicate(10, vec))
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 1 2 3 4 5
#> [2,] 1 2 3 4 5
#> [3,] 1 2 3 4 5
#> [4,] 1 2 3 4 5
#> [5,] 1 2 3 4 5
#> [6,] 1 2 3 4 5
#> [7,] 1 2 3 4 5
#> [8,] 1 2 3 4 5
#> [9,] 1 2 3 4 5
#> [10,] 1 2 3 4 5
How do I (efficiently) add a vector to every row of a matrix in Julia?
Simply prepend .
to the +
which will allow per element addition:
matr .+ centre
How do I add a vector from a matrix into an empty matrix using for loop in python?
for ii in d:
yf.append(a[ii])
or
for row in a:
yf.append(row)
will clean up the list append
or
yf = [ii for ii in a]
Working example:
In [65]: a = np.linspace(1,30,30).reshape(3,10)
...: yf = []
...: d = [0,1,2]
...: for ii in d:
...: yf.append(a[ii])
...:
In [66]: yf
Out[66]:
[array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]),
array([11., 12., 13., 14., 15., 16., 17., 18., 19., 20.]),
array([21., 22., 23., 24., 25., 26., 27., 28., 29., 30.])]
Turn the list of arrays into an array with:
In [67]: np.array(yf)
Out[67]:
array([[ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.],
[11., 12., 13., 14., 15., 16., 17., 18., 19., 20.],
[21., 22., 23., 24., 25., 26., 27., 28., 29., 30.]])
or with a function in the concatenate/stack family:
In [69]: np.vstack(yf)
Out[69]:
array([[ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.],
[11., 12., 13., 14., 15., 16., 17., 18., 19., 20.],
[21., 22., 23., 24., 25., 26., 27., 28., 29., 30.]])
We often get SO questions where people try to use np.append
iteratively to do this, but this is harder to get right, and is slower. Repeated list append followed by one array construction at the end is better.
Python Numpy: Adding vector to existing matrix row
In [74]: A = np.arange(1,10).reshape(3,3); v = np.arange(1,4)
In [75]: A
Out[75]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [77]: v
Out[77]: array([1, 2, 3])
Expand A
to a (3,3,3):
In [78]: A[None,:,:].repeat(3,0)
Out[78]:
array([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]])
Do the same with v
:
In [79]: np.eye(3)
Out[79]:
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
In [80]: np.eye(3)[:,:,None]*v
Out[80]:
array([[[1., 2., 3.],
[0., 0., 0.],
[0., 0., 0.]],
[[0., 0., 0.],
[1., 2., 3.],
[0., 0., 0.]],
[[0., 0., 0.],
[0., 0., 0.],
[1., 2., 3.]]])
add the two:
In [81]: _78+_80
Out[81]:
array([[[ 2., 4., 6.],
[ 4., 5., 6.],
[ 7., 8., 9.]],
[[ 1., 2., 3.],
[ 5., 7., 9.],
[ 7., 8., 9.]],
[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 8., 10., 12.]]])
or in one step:
A+np.eye(3)[:,:,None]*v
Adding a vector to a specific row of a matrix with numpy
Lets assume you have 2 matrices:
import numpy as np
m1 = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9,]])
m2 = np.empty([8, 8])
m2.fill(0)
And a list of positions is defined:
li = [1, 3, 6]
The list defines to replace values of the matrix m2
, by the rows of the matrix m1
, at the positions [0][0:2]
, [2][2:4]
and [5][5:7]
.
Values of numpy arrays can be replaced by numpy.put()
.
Calculate the indices of the values to be replaced and replace the values:
ri = [(v-1) * m2.shape[1] + v - 1 + j for v in li for j in range(m1.shape[1])]
np.put(m2, ri, m1)
Output:
print(m1)
print(li)
print(m2)
[[1 2 3]
[4 5 6]
[7 8 9]]
[1, 3, 6]
[[1. 2. 3. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 4. 5. 6. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 7. 8. 9.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]]
If you don't want to replace the indices, but you wat to add the values to the current matrix, then you have to sum the values in a loop, instead of replacing by np.put
:
for i in range(len(ri)):
m2.flat[ri[i]] += m1.flat[i]
How to append a vector as a column in R matrix?
use cbind
cbind(c(1,2), matrix(1:6, nrow=2))
So in case you work with bigger data, imagine your matrix is saved as m
and you have a vector my_vector
you want to add as a column in front of this matrix, the command would be
new_m <- cbind(my_vector, m)
Make sure the dimension of your vector fit the number of rows in your matrix.
In case you want to add rows instead of columns, the command is called rbind
and is used in exactly the same way.
How to add matrix and vector column-wise?
Make the vector a column:
matrix + vector[:, None]
Related Topics
Determine Season from Date Using Lubridate in R
How to Add Gaussian Curve to Histogram Created with Qplot
Linear Model with 'Lm': How to Get Prediction Variance of Sum of Predicted Values
Simple R 3D Interpolation/Surface Plot
Using Pivot_Longer with Multiple Paired Columns in the Wide Dataset
Create Link to the Other Part of the Shiny App
Ggplot Geom_Bar: Stack and Center
Combine Multiple .Rdata Files Containing Objects with the Same Name into One Single .Rdata File
How to Perform a Pairwise T.Test in R Across Multiple Independent Vectors
Calculate Summary Statistics (E.G. Mean) on All Numeric Columns Using Data.Table
Extracting Zip+CSV File from Attachment W/ Image in Body of Email
Remove Duplicate Rows from Xts Object
How to Install R-Packages Not in the Conda Repositories
How Is Data Passed from Reactive Shiny Expression to Ggvis Plot
Print R-Squared for All of the Models Fit with Lmlist
Importing Multiple Excel Files with Filenames in R
R Dataframe: Aggregating Strings Within Column, Across Rows, by Group