S
S
s1lver0k2017-04-11 13:31:12
Python
s1lver0k, 2017-04-11 13:31:12

Python. How to write a function to fill a matrix by condition?

The condition itself for filling:
Cij = 22/(i+j)
i - row
j - column

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
nirvimel, 2017-04-11
@s1lver0k

The first rule of numpy is NO CYCLES!

from time import time
import numpy
from numpy.lib.stride_tricks import as_strided

def fill_matrix_python(width, height):
    i, j = numpy.mgrid[0:height, 0:width]
    return 22. / (i + j + 2)

def fill_matrix_native(width, height):
    array = numpy.arange(2, width + height + 2)
    stride = array.strides[0]
    view_2d = as_strided(array,
                         shape=(width, height),
                         strides=(stride, stride))
    return 22. / view_2d

start_time = time()
fill_matrix_python(10000, 10000)
print('Python implementation: Matrix 10000x10000 filled in %.3f seconds' % (time() - start_time))

start_time = time()
fill_matrix_native(10000, 10000)
print('Native implementation: Matrix 10000x10000 filled in %.3f seconds' % (time() - start_time))

Python implementation: Matrix 10000x10000 filled in 3.332 seconds
Native implementation: Matrix 10000x10000 filled in 0.532 seconds

A more beautiful solution through mgrid under the hood is still implemented through script cycles (thanks to SkiBY for the comment).
A less beautiful solution through the manipulation of strides is implemented completely natively.

A
Astrohas, 2017-04-11
@Astrohas

def fill(c, width, height):
    for i in range(height):
        for j in range(width):
            c[i][j] = round(22/(i+j+2), 1)
    return c


a = [[0]*5 for _ in range(5)]
for i in fill(a, 5, 5):
    print(i)

G
gill-sama, 2017-04-11
@gill-sama

without numpy something like this

def create_matrix(h, w):
  a = []
  for i in range(h):
    a.append([])
    for j in range(w):
      a[i].append(22/(i+j+2))
  return a

S
SkiBY, 2017-04-11
@SkiBY

def fill(width, height):
    if width==0 or height == 0:
        return u'Матрица фуфуфу'
    c=[]
    for i in range(height-1):
        c.append([])
        for j in range(width-1):
            c[i].append(22/(i+j+2))
    return c

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question