1

I am working on a Python code so that I can basically do this with a Numpy Array

enter image description here

I have a Matlab code for it, which is

A = [1:30]'; % Example matrix
rows = 3;

for i=1:(numel(A)-rows+1)
    B(1:rows,i)=A(i:i+rows-1,1);
end

or, without any loop,

B = conv2(A.', flip(eye(rows)));

B = B(:, rows:end-rows+1);

Can someone help me do the same in Python? Using the reshape function is not helping since I need to "mirror" the values (and not only reorganizing them).

Thank you.

2
  • Is this a NumPy array? Commented Jun 20, 2018 at 19:24
  • @miradulo yes its a NumPy array miradulo Commented Jun 20, 2018 at 19:50

4 Answers 4

2

not very sexy but no for

import numpy as np

a = np.arange(1,31)
b = np.arange(3).reshape(3,1)
c = b+a[:28]

trying to translate your matlab code

import numpy as np
from scipy.signal import convolve2d

a = np.arange(1,31).reshape(1,30)
b = np.flip(np.eye(3,28),0)
c = convolve2d(a, b)[:,2:28]
Sign up to request clarification or add additional context in comments.

Comments

0

Using np.ndarray.reshape:

import numpy as np

A = np.arange(1, 31)
B = A.reshape((3, 10))

print(B)

[[ 1  2  3  4  5  6  7  8  9 10]
 [11 12 13 14 15 16 17 18 19 20]
 [21 22 23 24 25 26 27 28 29 30]]

Comments

0

This is the code for you.

import numpy as np

A = np.array(list(range(1,31)))

rows = 3

new_A = np.zeros((rows,A.size-rows+1))

for i in range(rows):
    new_A[i,:] = A[i:A.size-rows+i+1]

print (new_A)    

Comments

0

Try that code snippet:

import numpy as np
start = 1
end = 30
b_dim = 28

a = np.arange(start, end+1)
b = np.zeros((3, b_dim))

print("a = ", a)

rows, _ = b.shape

for row in range(rows):
    data = a[row:row+b_dim]
    b[row, :] = data

print("b = ", b)

it prints

('a = ', array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]))
('b = ', array([[  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,
         12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,
         23.,  24.,  25.,  26.,  27.,  28.],
       [  2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,  12.,
         13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,  23.,
         24.,  25.,  26.,  27.,  28.,  29.],
       [  3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,  12.,  13.,
         14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,  23.,  24.,
         25.,  26.,  27.,  28.,  29.,  30.]]))

2 Comments

that's my sloppy 8 =)
hey no worries!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.