How can I subtract a vector of each row in a array?
a <- array(1:8, dim=c(2,2,2))
a
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8
Using apply gives me:
apply(a,c(1,2), '-',c(1,5))
, , 1
[,1] [,2]
[1,] 0 1
[2,] 0 1
, , 2
[,1] [,2]
[1,] 2 3
[2,] 2 3
What I am trying to get is:
, , 1
[,1] [,2]
[1,] 0 -2
[2,] 1 -1
, , 2
[,1] [,2]
[1,] 4 2
[2,] 5 3
Thanks in advance for any hints
The most straightforward way to subtract two matrices in NumPy is by using the - operator, which is the simplification of the np. subtract() method - NumPy specific method designed for subtracting arrays and other array-like objects such as matrices.
Find the minimum non-zero element in the array, print it and then subtract this number from all the non-zero elements of the array. If all the elements of the array are < 0, just print 0.
subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise. Parameters : arr1 : [array_like or scalar]1st Input array. arr2 : [array_like or scalar]2nd Input array.
Use sweep
to operate on a particular margin of the array: rows are the second dimension (margin).
sweep(a,MARGIN=2,c(1,5),FUN="-")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With