2D matrix operation (subtraction)

Andre Pany andre at s-e-a-p.de
Fri Feb 21 13:42:24 UTC 2020


On Friday, 21 February 2020 at 11:53:02 UTC, Ali Çehreli wrote:
> 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

Thanks a lot. Mir is great and actually I try to rewrite some 
Python
Pandas Dataframe index logic. For my current project any 
dependency less
is a little headache less, therefore I try to avoid Mir at the 
moment,
but will definitely will have a look whether I can use it.

Thanks for the example, I will use it.

Kind regards
André




More information about the Digitalmars-d-learn mailing list