forked from wdmapp/gtensor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmult_table.cxx
82 lines (67 loc) · 2.03 KB
/
mult_table.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <gtensor/gtensor.h>
template <typename Ea, typename Eb>
auto outer_product(const Ea& a, const Eb& b)
{
int n = a.shape(0);
assert(n == b.shape(0));
return gt::eval(gt::reshape(a, gt::shape(1, n)) *
gt::reshape(b, gt::shape(n, 1)));
}
template <typename Ea, typename Eb>
auto outer_product_expr(const Ea& a, const Eb& b)
{
int n = a.shape(0);
assert(n == b.shape(0));
return gt::reshape(a, gt::shape(1, n)) * gt::reshape(b, gt::shape(n, 1));
}
int main(int argc, char** argv)
{
const int n = 9;
std::cout << "element access" << std::endl;
gt::gtensor<int, 2> mult_table(gt::shape(n, n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
mult_table(i, j) = (i + 1) * (j + 1);
}
}
for (int i = 0; i < n; i++) {
std::cout << mult_table.view(i, gt::all) << std::endl;
}
std::cout << std::endl;
std::cout << "broadcast" << std::endl;
gt::gtensor<int, 2> a(gt::shape(1, n));
gt::gtensor<int, 2> b(gt::shape(n, 1));
for (int i = 0; i < n; i++) {
a(0, i) = i + 1;
b(i, 0) = i + 1;
}
gt::gtensor<int, 2> ab = a * b;
for (int i = 0; i < n; i++) {
std::cout << ab.view(i, gt::all) << std::endl;
}
std::cout << std::endl;
std::cout << "broadcast with reshape" << std::endl;
gt::gtensor<int, 1> v(gt::shape(n));
for (int i = 0; i < n; i++) {
v(i) = i + 1;
}
gt::gtensor<int, 2> vv =
gt::reshape(v, gt::shape(1, n)) * gt::reshape(v, gt::shape(n, 1));
for (int i = 0; i < n; i++) {
std::cout << vv.view(i, gt::all) << std::endl;
}
std::cout << std::endl;
std::cout << "broadcast with reshape (helper fn)" << std::endl;
gt::gtensor<int, 2> vv2 = outer_product(v, v);
for (int i = 0; i < n; i++) {
std::cout << vv2.view(i, gt::all) << std::endl;
}
std::cout << std::endl;
std::cout << "broadcast with reshape (helper fn expr)" << std::endl;
auto vv_expr = outer_product_expr(v, v);
auto vv3 = gt::eval(vv_expr);
for (int i = 0; i < n; i++) {
std::cout << vv3.view(i, gt::all) << std::endl;
}
}