Skip to content

2 Create a Matrix

Süleyman Özarslan edited this page Sep 14, 2022 · 1 revision

You can create matrices in different ways by using the functions in the Matrix package.

Create a Custom Matrix

You can create a matrix with the values you give by creating a new object.

customMatrix := matrix.Matrix{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} // 3x3 Matrix

As a result, you have a 3x3 matrix of the values you provided. You can access all the methods of the Matrix package through this object. You can use the Print command instead of the fmt package for printing in the terminal. Thus, you can make the matrix you have obtained look more regularly.

customMatrix.Print()
1 2 3
4 5 6
7 8 9

Create a Zero Matrix

func Zeros(row_count, col_count int) Matrix

The 'Zeros' function can be used to create a matrix of the desired size and all values of 0.

zeroMatrix := matrix.Zeros(4, 4)
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

Create a Matrix With a Specific Value

func GenerateRand(row_count, col_count int) Matrix

The Generate function can be used to create a matrix with desired size and given value.

ones := matrix.Generate(2, 2, 1)
1 1
1 1

Create a Matrix of Random Values

func GenerateRand(row_count, col_count int) Matrix

The GenerateRand function can be used to create a matrix of desired size and random values.

random := matrix.GenerateRand(2, 2)
60.49 94.05
66.45 43.77

Create a Unit Matrix

func UnitMatrix(row_count, col_count int) Matrix

UnitMatrix function can be used to create a Unit matrix of desired size.

unit := matrix.UnitMatrix(3, 3)
1 0 0
0 1 0
0 0 1