slicing.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // -*- mode: c++; coding: utf-8 -*-
  2. // ra-ra/examples - Slicing
  3. // Daniel Llorens - 2015
  4. // Adapted from blitz++/examples/slicing.cpp
  5. #include "ra/ra.hh"
  6. #include <iostream>
  7. using std::cout, std::endl, std::flush;
  8. int main()
  9. {
  10. ra::Big<int, 2> A({6, 6}, 99);
  11. // Set the upper left quadrant of A to 5
  12. A(ra::iota(3), ra::iota(3)) = 5;
  13. // Set the upper right quadrant of A to an identity matrix
  14. A(ra::iota(3), ra::iota(3, 3)) = { 1, 0, 0, 0, 1, 0, 0, 0, 1 };
  15. // Set the fourth row to 1 (any of these ---trailing ra::all can be omitted).
  16. A(3, ra::all) = 1;
  17. A(ra::iota(1, 3), ra::all) = 1;
  18. A(3) = 1;
  19. // Set the last two rows to 0. These are equivalent.
  20. // ra::len represents the length of the subscribed axis, so iota(2, len-2) means the last 2 indices on that axis.
  21. A(ra::iota(2, ra::len-2), ra::all) = 0;
  22. A(ra::iota(2, ra::len-2)) = 0;
  23. // ra::len cannot be an array element, but the following is valid (and equivalent to the previous two).
  24. A(ra::len + std::array { -2, -1 }) = 0;
  25. // Set the bottom right element to 8. These are equivalent.
  26. A(5, 5) = 8;
  27. A(ra::len-1, ra::len-1) = 8;
  28. cout << "\nA = " << A << endl;
  29. // Demonstrating multi-axis selectors. Use these to skip over any number of
  30. // axes, just as ra::all skips over one axis.
  31. ra::Big<int, 3> B({3, 5, 5}, 99);
  32. // These are equivalent.
  33. B(ra::all, ra::all, 2) = 3.;
  34. B(ra::dots<2>, 2) = 3.;
  35. B(ra::dots<>, 2) = 3.;
  36. // These are all equivalent.
  37. B(1, ra::all, ra::all) = 7.;
  38. B(1) = 7.;
  39. B(1, ra::dots<2>) = 7.;
  40. // Under c++23 you can use [] instead of () for multi-indices. Single index [] works in any case.
  41. #if __cpp_multidimensional_subscript >= 202110L
  42. B[1, ra::all, ra::all] = 7.;
  43. B[1] = 7.;
  44. B[1, ra::dots<2>] = 7.;
  45. #endif
  46. // These are equivalent.
  47. B(2, ra::all, 1) = 5.;
  48. B(2, ra::dots<1>, 1) = 5.;
  49. // These are equivalent.
  50. B(0, 2, 3) = 1.;
  51. B(ra::dots<0>, 0, ra::dots<0>, 2, ra::dots<0>, 3, ra::dots<0>) = 1.;
  52. cout << "\nB = " << B << endl;
  53. return 0;
  54. }