Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum values of array in each dimension into one matrix

Tags:

r

matrix

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!

like image 784
burton030 Avatar asked Jan 23 '14 07:01

burton030


People also ask

How do you get the sum of all values in a matrix?

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.

How do you sum values in an array?

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.

How do you sum all elements in a matrix in python?

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.


1 Answers

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
like image 51
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 03 '22 00:11

A5C1D2H2I1M1N2O1R2T1