Straight brackets (brackets) wrong?

0

I have this function in Matlab

cn = reshape(repmat(sn, n_rep, 1), 1,[]);

In Python I have the following code:

import numpy as np
from numpy.random import randint

M=2
N=2*10**8 ### valor de Dados
n_rep = 3 ## numero de repetições
sn = randint(0,M,size = N)### Inteiros 0 e 1
print("sn=", sn)
cn_repmat=np.tile(sn,n_rep)
print("cn_repmat=", cn_repmat)
cn=np.reshape(cn_repmat,1,[])
print(cn)

I'm not sure if the right parentheses in python are like this because it gives me the following error

  File "C:/Users/Sergio Malhao/.spyder-py3/Desktop/untitled6.py", line 17, in <module>
    cn=np.reshape(cn_repmat,1,[])

  File "E:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py", line 232, in reshape
    return _wrapfunc(a, 'reshape', newshape, order=order)

  File "E:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py", line 57, in _wrapfunc
    return getattr(obj, method)(*args, **kwds)

ValueError: cannot reshape array of size 600000000 into shape (1,)
    
asked by anonymous 07.10.2017 / 00:27

1 answer

1

The problem is syntax. You copied the code without looking at what the python function uses as input.

With a look at the manual you can see that to a direct copy matlab-> python does not work.

The error:

  

ValueError: can not reshape array of size 600000000 into shape (1,)

It is exactly because the format that was given as input is not accepted.

What you should use is

cn=np.reshape(cn_repmat,(Linhas,Colunas))

In your case, since the intention is to have only one row, the -1 entry for the columns value is ideal. This entry in this function has the same effect as [] of matlab, thus:

cn=np.reshape(cn_repmat,(1,-1))

However, this function does not seem to me necessary given your code. Because tile is only copying an array of one line sn n_rep times on the same line.

Looking at the data

Looking at the data entry / output of the initial expression we have:

a=1:4
reshape(repmat(a, 4, 1), 1,[])
ans =
[ 1  1  1  1  2  2  2  2  3  3  3  3  4  4  4  4 ]

in python

b=np.array([1,2,3,4])
np.reshape(np.tile(b,(4,1)),(1,-1))
>array([[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]])

So this does not work. However, all you need to do is to use the% trans_ed array that is in the same order as matlab.

np.reshape(np.tile(b,(4,1)).T,(1,-1))
>array([[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]]) 

Another option is to also use cn_repmat.T , which does exactly how you want it to still have the FORTRAN option ravel that reads the column-wise array:

np.tile(b,(4,1)).ravel(order='F')
>array([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4])
    
07.10.2017 / 01:01