2

I have a question about typed array initialization in IronPython. I want to initialize inline typed two-dimensional array in IronPython.
In IronPython I discovered how to initialize simple typed array:

pythonTypedArray = Array[int]([0, 1, 2, 3, 4])

and how to initialize typed array of arrays:

pythonTypedArrayOfArrays = Array[Array[int]]([Array[int]([0, 1]), Array[int]([2, 3])])

For example, in C# I can do like so:

int[,] twoDimensionalArray = new int[,] { {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9} };

Can I initialize inline two-dimensional typed array in IronPython? If no, what is the best way to initialize two-dimensional typed array in IronPython?

Bill
  • 3,391
  • 3
  • 13
  • 17

2 Answers2

2

So, you need a matrix. In Python it can be achieved by doing this:

matrix = [[0 for x in range(w)] for y in range(h)] 

Or using numpy (you can install it by running pip install numpy):

>>> import numpy
>>> numpy.zeros((4, 4))
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

In numpy, generating a matrix with random numbers is as simple as:

>>> import numpy as np
>>> np.random.rand(2,3)
array([[ 0.22568268,  0.0053246 ,  0.41282024],
       [ 0.68824936,  0.68086462,  0.6854153 ]])

IMO, whenever you want matrices, you want to use numpy because it has some nice methods which really help you process them.


//EDIT: Since you added more context, in IronPython you can create an array of arrays by doing:

array = Array[Array[int]]( ( (1,2), (3,4) ) )

or you can create multidimensional arrays is to use Array.CreateInstance passing type as a first argument followed by dimension sizes:

array = Array.CreateInstance(int, 2, 3)

You can always read the docs when you need more information

0
import numpy
a = numpy.arange(12)
a.shape = 3,  4
print(a)
>>>
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
Rahul
  • 10,830
  • 4
  • 53
  • 88
  • Could you provide any information on how can I install numpy? I've tried instructions from this link, but it does not work(Could not download ironpkg-1.0.0.py file): https://stackoverflow.com/questions/29397540/how-to-install-numpy-and-scipy-for-ironpython27-old-method-doenst-work – Bill Jul 04 '17 at 14:35
  • It's Tricky. Use scientific python instead. like Anaconda, WinPython, Just google it. They have numpy and the like pre-installed. – Rahul Jul 04 '17 at 15:40