gorgonia.org/tensor@v0.9.24/example_iterator_test.go (about)

     1  package tensor
     2  
     3  import "fmt"
     4  
     5  // This is an example of how to use `IteratorFromDense` from a row-major Dense tensor
     6  func Example_iteratorRowmajor() {
     7  	T := New(WithShape(2, 3), WithBacking([]float64{0, 1, 2, 3, 4, 5}))
     8  	it := IteratorFromDense(T)
     9  	fmt.Printf("T:\n%v\n", T)
    10  
    11  	for i, err := it.Start(); err == nil; i, err = it.Next() {
    12  		fmt.Printf("i: %d, coord: %v\n", i, it.Coord())
    13  	}
    14  
    15  	// Output:
    16  	// T:
    17  	// ⎡0  1  2⎤
    18  	// ⎣3  4  5⎦
    19  	//
    20  	// i: 0, coord: [0 1]
    21  	// i: 1, coord: [0 2]
    22  	// i: 2, coord: [1 0]
    23  	// i: 3, coord: [1 1]
    24  	// i: 4, coord: [1 2]
    25  	// i: 5, coord: [0 0]
    26  
    27  }
    28  
    29  // This is an example of using `IteratorFromDense` on a col-major Dense tensor. More importantly
    30  // this example shows the order of the iteration.
    31  func Example_iteratorcolMajor() {
    32  	T := New(WithShape(2, 3), WithBacking([]float64{0, 1, 2, 3, 4, 5}), AsFortran(nil))
    33  	it := IteratorFromDense(T)
    34  	fmt.Printf("T:\n%v\n", T)
    35  
    36  	for i, err := it.Start(); err == nil; i, err = it.Next() {
    37  		fmt.Printf("i: %d, coord: %v\n", i, it.Coord())
    38  	}
    39  
    40  	// Output:
    41  	// T:
    42  	// ⎡0  2  4⎤
    43  	// ⎣1  3  5⎦
    44  	//
    45  	// i: 0, coord: [0 1]
    46  	// i: 2, coord: [0 2]
    47  	// i: 4, coord: [1 0]
    48  	// i: 1, coord: [1 1]
    49  	// i: 3, coord: [1 2]
    50  	// i: 5, coord: [0 0]
    51  
    52  }
    53  
    54  func ExampleSliceIter() {
    55  	T := New(WithShape(3, 3), WithBacking(Range(Float64, 0, 9)))
    56  	S, err := T.Slice(makeRS(1, 3), makeRS(1, 3))
    57  	if err != nil {
    58  		fmt.Printf("Err %v\n", err)
    59  		return
    60  	}
    61  	fmt.Printf("S (requires iterator? %t)\n%v\n", S.(*Dense).RequiresIterator(), S)
    62  	it := IteratorFromDense(S.(*Dense))
    63  	for i, err := it.Start(); err == nil; i, err = it.Next() {
    64  		fmt.Printf("i %d, coord %v\n", i, it.Coord())
    65  	}
    66  
    67  	// Output:
    68  	// S (requires iterator? true)
    69  	// ⎡4  5⎤
    70  	// ⎣7  8⎦
    71  	//
    72  	// i 0, coord [0 1]
    73  	// i 1, coord [1 0]
    74  	// i 3, coord [1 1]
    75  	// i 4, coord [0 0]
    76  
    77  }