tensor-0.1.0
 All Data Structures Namespaces Functions Variables Typedefs Enumerations Enumerator Groups Pages
tensor_change_dimension.cc
1 // -*- mode: c++; fill-column: 80; c-basic-offset: 2; indent-tabs-mode: nil -*-
2 /*
3  Copyright (c) 2010 Juan Jose Garcia Ripoll
4 
5  Tensor is free software; you can redistribute it and/or modify it
6  under the terms of the GNU Library General Public License as published
7  by the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU Library General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License along
16  with this program; if not, write to the Free Software Foundation, Inc.,
17  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 
20 #include <tensor/tensor.h>
21 #include <tensor/detail/common.h>
22 
23 namespace tensor {
24 
25  template<class Tensor>
26  static const Tensor change_dimension_inner(const Tensor &a, int dim, index new_size)
27  {
28  typedef typename Tensor::elt_t elt_t;
29 
30  dim = normalize_index(dim, a.rank());
31  Indices d = a.dimensions();
32  index old_size = d[dim];
33  if (old_size == new_size)
34  return a;
35 
36  d.at(dim) = new_size;
37  Tensor output(d);
38  elt_t *p1 = output.begin();
39  const elt_t *p2 = a.begin();
40  index i_len, k_len;
41  surrounding_dimensions(d, dim, &i_len, &new_size, &k_len);
42  if (old_size > new_size) {
43  output.fill_with_zeros();
44  index dp2 = (old_size - new_size) * i_len;
45  for (index k = 0; k < k_len; k++) {
46  for (index j = 0; j < new_size; j++) {
47  memcpy(p1, p2, i_len * sizeof(*p1));
48  p1 += i_len;
49  p2 += i_len;
50  }
51  p2 += dp2;
52  }
53  } else {
54  index dp1 = (new_size - old_size) * i_len;
55  for (index k = 0; k < k_len; k++) {
56  for (index j = 0; j < old_size; j++) {
57  memcpy(p1, p2, i_len * sizeof(*p1));
58  p1 += i_len;
59  p2 += i_len;
60  }
61  for (index i = 0; i < dp1; i++, p1++)
62  *p1 = number_zero<elt_t>();
63  }
64  }
65  return output;
66  }
67 
68 } // namespace tensor