I've one array with three dimensions and want to sum up the values in each dimension and end up with one data matrix.
Here is one example:
array1 <- array(c(-5.5,6,3),dim = c(3,4,3))
matrix <- matrix(NA, nrow=3, ncol=4)
matrix
[,1] [,2] [,3] [,4]
[1,] -16.5 -16.5 -16.5 -16.5
[2,] 18 18 18 18
[3,] 9 9 9 9
Is it possible to do it somehow with a loop instead of using any apply function?
Thanks in advance!
S = sum( A , 'all' ) computes the sum of all elements of A . This syntax is valid for MATLAB® versions R2018b and later. S = sum( A , dim ) returns the sum along dimension dim . For example, if A is a matrix, then sum(A,2) is a column vector containing the sum of each row.
You can find the sum of all elements in an array by following the approach below: Initialize a variable sum to store the total sum of all elements of the array. Traverse the array and add each element of the array with the sum variable. Finally, return the sum variable.
Python numpy sum() function syntax The array elements are used to calculate the sum. If the axis is not provided, the sum of all the elements is returned. If the axis is a tuple of ints, the sum of all the elements in the given axes is returned. We can specify dtype to specify the returned output data type.
Your question says you don't want to use an apply
function, but in case you change your mind, you specify the margin as c(1, 2)
:
apply(array1, MARGIN=c(1, 2), sum)
# [,1] [,2] [,3] [,4]
# [1,] -16.5 -16.5 -16.5 -16.5
# [2,] 18.0 18.0 18.0 18.0
# [3,] 9.0 9.0 9.0 9.0
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