Linear array to matrix

9il ilyayaroshenko at gmail.com
Sat Apr 4 14:00:01 UTC 2020


On Saturday, 4 April 2020 at 09:25:14 UTC, Giovanni Di Maria 
wrote:
> Hi.
> Is there a Built-in function (no code, only a built-in function)
> that transform a linear array to a Matrix?
>
> For example:
>
> From
>
> [10,20,30,40,50,60,70,80,90,100,110,120];
>
>
> To
>
> [
> [10,20,30],
> [40,50,60],
> [70,80,90],
> [100,110,120]
> ];
>
> Thank You very much
> Cheers.
> Giovanni

You may want to look into a mir-algorithm package that supports 
rectangular multidimensional arrays like NumPy.

/+dub.sdl:
dependency "mir-algorithm" version="~>3.7.27"
+/

// http://mir-algorithm.libmir.org/mir_ndslice.html

import mir.ndslice;

void main()
{
     //
     auto intArray = [10,20,30,40,50,60,70,80,90,100,110,120];
     auto intMatrix = intArray.sliced(4, 3);

     static assert(is(typeof(intMatrix) == Slice!(int*, 2)));

     // lazy matrix
     auto lazyMatrix = iota!int([4, 3]/*shape*/, 10/*start*/, 
10/*stride*/);
     assert(intMatrix == lazyMatrix);
     //or
     foreach(i; 0 .. intMatrix.length)
     	foreach(j; 0 .. intMatrix.length!1)
         	assert(intMatrix[i, j] == lazyMatrix[i, j]);
         	
}



More information about the Digitalmars-d-learn mailing list