I have this function in matlab
cn = reshape (repmat (sn, n_rep, 1), 1, []);
No python with the key code:
import numpy like np
from numpy.random import randint
M = 2
N = 2 * 10 ** 8 ### data value
n_rep = 3 ## number of repetitions
sn = randint (0, M, size = N) ### integers 0 and 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 retro kinship is not known
File "C: / Users / Sergio Malhao / .spyder-py3 / Desktop / untitled6.py", line 17, under <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: Can not reshape the array of size 600000000 in shape (1,)
Numpy is not supposed to be a 1:1 matlab. It works similar, but not in the same way. I assume you want to convert a matrix into one dimensional array.
Try to:
np.reshape (cn_repmat, (1, -1))
where the (1, -1) is a tuple defining size of the new array.
One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
In Octave:
>> sn = [0,1,2,3,4]
sn =
0 1 2 3 4
>> repmat(sn,4,1)
ans =
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
>> reshape(repmat(sn,4,1),1,[])
ans =
0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
In numpy
:
In [595]: sn=np.array([0,1,2,3,4])
In [596]: np.repeat(sn,4)
Out[596]: array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4])
In [597]: np.tile(sn,4)
Out[597]: array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4])
In MATLAB matrices are at least 2d; in numpy they may be 1d. Out[596]
is 1d.
We could get closer to the MATLAB by making the sn
2d:
In [608]: sn2 = sn[None,:] # = sn.reshape((1,-1))
In [609]: sn2
Out[609]: array([[0, 1, 2, 3, 4]])
In [610]: np.repeat(sn2,4,1)
Out[610]: array([[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]])
With tile
we have to transpose or play order games (MATLAB is order F):
In [613]: np.tile(sn,[4,1])
Out[613]:
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
In [614]: np.tile(sn,[4,1]).T.ravel()
Out[614]: array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4])
In [615]: np.tile(sn,[4,1]).ravel(order='F')
Out[615]: array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4])
ravel
is the equivalent of reshape(...., -1)
. -1
functions like []
in MATLAB when reshaping.
In numpy
repeat
is the basic function; tile
uses repeat
with a different user interface (more like repmat
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.