github.com/jingcheng-WU/gonum@v0.9.1-0.20210323123734-f1a2a11a8f7b/mat/vector_example_test.go (about)

     1  // Copyright ©2019 The Gonum Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package mat_test
     6  
     7  import (
     8  	"fmt"
     9  
    10  	"github.com/jingcheng-WU/gonum/blas/blas64"
    11  	"github.com/jingcheng-WU/gonum/mat"
    12  )
    13  
    14  // This example shows how simple user types can be constructed to
    15  // implement basic vector functionality within the mat package.
    16  func Example_userVectors() {
    17  	// Perform the cross product of [1 2 3 4] and [1 2 3].
    18  	r := row{1, 2, 3, 4}
    19  	c := column{1, 2, 3}
    20  
    21  	var m mat.Dense
    22  	m.Mul(c, r)
    23  
    24  	fmt.Println(mat.Formatted(&m))
    25  
    26  	// Output:
    27  	//
    28  	// ⎡ 1   2   3   4⎤
    29  	// ⎢ 2   4   6   8⎥
    30  	// ⎣ 3   6   9  12⎦
    31  }
    32  
    33  // row is a user-defined row vector.
    34  type row []float64
    35  
    36  // Dims, At and T minimally satisfy the mat.Matrix interface.
    37  func (v row) Dims() (r, c int)    { return 1, len(v) }
    38  func (v row) At(_, j int) float64 { return v[j] }
    39  func (v row) T() mat.Matrix       { return column(v) }
    40  
    41  // RawVector allows fast path computation with the vector.
    42  func (v row) RawVector() blas64.Vector {
    43  	return blas64.Vector{N: len(v), Data: v, Inc: 1}
    44  }
    45  
    46  // column is a user-defined column vector.
    47  type column []float64
    48  
    49  // Dims, At and T minimally satisfy the mat.Matrix interface.
    50  func (v column) Dims() (r, c int)    { return len(v), 1 }
    51  func (v column) At(i, _ int) float64 { return v[i] }
    52  func (v column) T() mat.Matrix       { return row(v) }
    53  
    54  // RawVector allows fast path computation with the vector.
    55  func (v column) RawVector() blas64.Vector {
    56  	return blas64.Vector{N: len(v), Data: v, Inc: 1}
    57  }