tensor-0.1.0
 All Data Structures Namespaces Functions Variables Typedefs Enumerations Enumerator Groups Pages
tensor_mean_ndx.cc
1 /*
2  Copyright (c) 2010 Juan Jose Garcia Ripoll
3 
4  Tensor is free software; you can redistribute it and/or modify it
5  under the terms of the GNU Library General Public License as published
6  by the Free Software Foundation; either version 2 of the License, or
7  (at your option) any later version.
8 
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU Library General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License along
15  with this program; if not, write to the Free Software Foundation, Inc.,
16  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17 */
18 
19 #include <tensor/tensor.h>
20 #include <tensor/detail/common.h>
21 
22 namespace {
23 
24  using namespace tensor;
25 
26  template<typename Tensor>
27  Tensor do_mean(const Tensor &t, int ndx)
28  {
29  int rank = t.rank();
30  if (rank == 1) {
31  Tensor output(1);
32  output.at(0) = mean(t);
33  return output;
34  } else {
35  ndx = normalize_index(ndx, rank);
36  Indices dimensions(rank-1);
37  tensor::index left = 1, middle, right = 1;
38  for (int i = 0, j = 0; i < rank; i++) {
39  tensor::index d = t.dimension(i);
40  dimensions.at(j++) = d;
41  if (i < ndx)
42  left *= d;
43  else if (i > ndx)
44  right *= d;
45  else
46  middle = d;
47  }
48  Tensor aux = reshape(t, left, middle, right);
49  Tensor output = Tensor::zeros(dimensions);
50  for (tensor::index r = 0; r < right; r++)
51  for (tensor::index m = 0; m < middle; m++)
52  for (tensor::index l = 0; l < left; l++)
53  output.at(l,r) += aux(l,m,r);
54  return output / typename Tensor::elt_t(middle);
55  }
56  }
57 
58 } // namespace tensor
int rank() const
Number of Tensor indices.
Definition: tensor.h:119
An N-dimensional array of numbers.
Definition: tensor.h:47
static const Tensor< elt_t > zeros(index rows)
Matrix of zeros.
Definition: tensor.h:235
const RTensor reshape(const RTensor &t, const Indices &new_dims)
Return a RTensor with same data and given dimensions.
Vector of 'index' type, where 'index' fits the indices of a tensor.
Definition: indices.h:35
index dimension(int which) const
Length of a given Tensor index.
elt_t & at(index i)
Return a mutable reference to an element of a 1D Tensor.