Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define matrix in solidity?

I want to define matrix in solidity. First I try to define 1×3 matrix like this

contract test{
    uint8[5] public uintArray = [1, 2, 3];

but, this array allows me to take only an element.

ex)uintArray(0) ---> 1
   uintArray(1) ---> 2
   uintArray(2) ---> 3

Please teach me how to define matrix in solidity.

Additional note: I want to use a more complex matrix finally, so I want to know more complex matrix like this.

[1 5 7
8 5 7
8 6 9]
like image 543
ushiwak Avatar asked Oct 20 '25 21:10

ushiwak


1 Answers

Multi-dimensional arrays are essentially nested arrays (An array that contain other arrays). These however, come in three forms in Solidity. We use two-dimensional array in this first example

T[k][k] : Two-Dimensional, Fixed-size
T[][] : Two-Dimensional, Dynamic-size
T[][k] or T[k][] : Two-Dimensional, Mixed-size

but you will see that multi-dimensional arrays can have any level of nesting ! Here are some examples

T[2][2][2] : Three-Dimensional, Fixed-Size (all k are the same)
T[2][8][4][12] : Four-Dimensional, Fixed-Sizes ( k‘s are of different values)
T[][][][][] : Five-Dimensional, Dynamic-Size
T[][3][2][][9][] : Six-Dimensional, Mixed-Size

As you can see, dynamic-size and fixed-size can be mixed in a nested array. However, two important notes about nested array must be mentioned.

See a detail explanation and examples in these articles:

  • https://medium.com/@jeancvllr/solidity-tutorial-all-about-array-efdff4613694
  • https://hackernoon.com/arrays-in-solidity-b65c1326f48b
like image 99
Diego B Avatar answered Oct 24 '25 15:10

Diego B