On 2/21/20 12:51 AM, Andre Pany wrote:
Hi,

I have a 2D double array and I want to subtract from the first column a value,
is this possible with matrix operation in D?

```
void main()
{
     double[][] data = [[0.0, 1.4], [1.0, 5.2], [2.0, 0.8]];

     // subtract -2.0 from the first column for every value

     // Expected output
     // data = [[-2.0, 1.4], [-1.0, 5.2], [0.0, 0.8]];

}
```

Kind regards
André




I don't have experience with it but mir's ndslice is designed for this:

  https://github.com/libmir/mir-algorithm

Although it feels like something similar is probably already in Phobos, I've come up with the following solution just now for fun:

import std.stdio;
import std.algorithm;
import std.range;

// At least something similar to this exists in Phobos?
struct ElementReference(R) {
  ElementType!(ElementType!R) * p;

  ref reference() {
    return *p;
  }

  alias reference this;
}

struct Column(R) {
  R range;
  size_t n;

  auto empty() {
    return range.empty;
  }

  auto front() {
    return ElementReference!R(&(range.front[n]));
  }

  auto popFront() {
    return range.popFront();
  }
}

auto byColumn(R)(R range, size_t n) {
  return Column!R(range, n);
}

void main() {
  double[][] data = [[0.0, 1.4], [1.0, 5.2], [2.0, 0.8]];

  data.byColumn(0).each!(a => a -= 2.0);
  writeln(data);
}

Ali

Reply via email to