SHOGUN  v2.0.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
SGNDArray.h
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 3 of the License, or
5  * (at your option) any later version.
6  *
7  * Written (W) 2012 Fernando José Iglesias García
8  * Written (W) 2010,2012 Soeren Sonnenburg
9  * Copyright (C) 2010 Berlin Institute of Technology
10  * Copyright (C) 2012 Soeren Sonnenburg
11  */
12 
13 #ifndef __SGNDARRAY_H__
14 #define __SGNDARRAY_H__
15 
16 #include <shogun/lib/config.h>
17 #include <shogun/lib/DataType.h>
18 
19 namespace shogun
20 {
22 template<class T> class SGNDArray
23 {
24  public:
26  SGNDArray() : array(NULL), dims(NULL), num_dims(0), do_free(false) { }
27 
29  SGNDArray(T* a, index_t* d, index_t nd, bool do_free_ndarray = false)
30  : array(a), dims(d), num_dims(nd), do_free(do_free_ndarray) { }
31 
33  SGNDArray(index_t* d, index_t nd, bool do_free_ndarray = false)
34  : dims(d), num_dims(nd), do_free(do_free_ndarray)
35  {
36  index_t tot = 1;
37  for (int32_t i=0; i<nd; i++)
38  tot *= dims[i];
39  array=SG_MALLOC(T, tot);
40  }
41 
43  SGNDArray(const SGNDArray &orig)
44  : array(orig.array), dims(orig.dims), num_dims(orig.num_dims),
45  do_free(orig.do_free) { }
46 
48  virtual ~SGNDArray()
49  {
50  }
51 
53  virtual void free_ndarray()
54  {
55  if (do_free)
56  SG_FREE(array);
57 
58  SG_FREE(dims);
59 
60  array = NULL;
61  dims = NULL;
62  num_dims = 0;
63  }
64 
65 
67  virtual void destroy_ndarray()
68  {
69  do_free = true;
70  free_ndarray();
71  }
72 
78  T* get_matrix(index_t matIdx) const
79  {
80  ASSERT(array && dims && num_dims > 2 && dims[2] > matIdx);
81  return &array[matIdx*dims[0]*dims[1]];
82  }
83 
88  inline const T& operator[](index_t index) const
89  {
90  return array[index];
91  }
92 
97  inline T& operator[](index_t index)
98  {
99  return array[index];
100  }
101 
106  void transpose_matrix(index_t matIdx) const
107  {
108  ASSERT(array && dims && num_dims > 2 && dims[2] > matIdx);
109 
110  T aux;
111  // Index to acces directly the elements of the matrix of interest
112  int32_t idx = matIdx*dims[0]*dims[1];
113 
114  for (int32_t i=0; i<dims[0]; i++)
115  for (int32_t j=0; j<i-1; j++)
116  {
117  aux = array[idx + i + j*dims[0]];
118  array[idx + i + j*dims[0]] = array[idx + j + i*dims[0]];
119  array[idx + j + i*dims[1]] = aux;
120  }
121 
122  // Swap the sizes of the two first dimensions
123  index_t auxDim = dims[0];
124  dims[0] = dims[1];
125  dims[1] = auxDim;
126  }
127 
128  public:
130  T* array;
136  bool do_free;
137 };
138 }
139 #endif // __SGNDARRAY_H__

SHOGUN Machine Learning Toolbox - Documentation