V
V
voronin_denis2019-07-26 10:26:16
Python
voronin_denis, 2019-07-26 10:26:16

How to expand a matrix by value python?

There is a longitude matrix, you need to add values ​​around each element.

Found the numpy.pad tool , but it adds elements around the matrix. And you need around each value, expanding the matrix.

For example, the matrix should become
[[[0.1, 0.2, 0.3],
[0.2, 1, 0.2],
[0.3, 0.2, 0.3], [...][ ...]
New setpoints should appear around 1, and so on.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
V
Vladimir Kuts, 2019-07-28
@voronin_denis

As an option:

import numpy as np

A = [[1,2], [3,4]]

def pad_el(el): 
    return np.stack( 
        ( 
            np.zeros(3), 
            np.pad([el], 1, mode='constant'), 
            np.zeros(3) 
        ), axis=1)

out_array = []
for i in range(len(A)): 
    row = [] 
    for j in range(len(A[i])):
        if len(row) == 0:
            row = pad_el(A[i][j])
        else:
            row = np.block([row, pad_el(A[i][j])])
    if len(out_array) == 0:
        out_array = row
    else:
        out_array = np.vstack((out_array, row))
print(out_array)

[[0. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 2. 0.]
 [0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0.]
 [0. 3. 0. 0. 4. 0.]
 [0. 0. 0. 0. 0. 0.]]

For
A = [[1,2,3], [3,4,5], [6,7,8]]
[[0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 2. 0. 0. 3. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 3. 0. 0. 4. 0. 0. 5. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 6. 0. 0. 7. 0. 0. 8. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]]

S
Sergey Tikhonov, 2019-07-26
@tumbler

  1. Reshape the matrix by pulling it out 1x(m*n)
  2. Making it 3D: 1x1x(MxN)
  3. We call numpy.pad on the first two axes (is it possible?)
  4. We do an inverse reshape, we get an MxN "tile" from two-dimensional 3x3 matrices.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question