How to sum multidimensional arrays?
    p.shkadzko 
    p.shkadzko at gmail.com
       
    Thu Feb 27 14:15:26 UTC 2020
    
    
  
I'd like to sum 2D arrays. Let's create 2 random 2D arrays and 
sum them.
```
import std.random : Xorshift, unpredictableSeed, uniform;
import std.range : generate, take, chunks;
import std.array : array;
static T[][] rndMatrix(T)(T max, in int rows, in int cols)
{
     Xorshift rnd;
     rnd.seed(unpredictableSeed);
     const amount = rows * cols;
     return generate(() => uniform(0, max, 
rnd)).take(amount).array.chunks(cols).array;
}
void main() {
     int[][] m1 = rndMatrix(10, 2, 3);
     int[][] m2 = rndMatrix(10, 2, 3);
     auto c = m1[] + m2[];
}
```
This won't work because the compiler will throw "Error: array 
operation m[] + m2[] without destination memory not allowed". 
Looking at 
https://forum.dlang.org/thread/wnjepbggivhutgbyjagm@forum.dlang.org, I modified the code to:
```
void main() {
     int[][] m1 = rndMatrix(10, 2, 3);
     int[][] m2 = rndMatrix(10, 2, 3);
     int[][] c;
     c.length = m[0].length;
     c[1].length = m[1].length;
	
     c[] = m1[] + m2[];
}
```
Well then I am getting
"/dlang/dmd/linux/bin64/../../src/druntime/import/core/internal/array/operations.d(165): Error: static assert:  "Binary + not supported for types int[] and int[]."
Right, then I am trying the following
```
void main() {
     int[][] m1 = rndMatrix(10, 2, 3);
     int[][] m2 = rndMatrix(10, 2, 3);
     auto c = zip(m[], m2[]).map!((a, b) => a + b);
}
```
Doesn't work either because
"Error: template D main.__lambda1 cannot deduce function from 
argument types !()(Tuple!(int[], int[])), candidates are:
onlineapp.d(21):        __lambda1
(...)
So, I have to flatten first, then zip + sum and then reshape back 
to the original.
```
auto c = zip(m.joiner, m2.joiner).map!(t => t[0] + 
t[1]).array.chunks(3).array;
```
This works but it does not look very efficient considering we 
flatten and then calling array twice. It will get even worse with 
3D arrays. Is there a better way without relying on mir.ndslice?
    
    
More information about the Digitalmars-d-learn
mailing list