1

I am trying to convert Matlab code into Python, but I'm receiving an error when I append zeros in my array.

Matlab Code:

N_bits=1e5;
a1=[0,1];
bits=a1(ceil(length(a1)*rand(1,N_bits)));
bits=[0 0 0 0 0 0 0 0 bits];

Python Code:

a1=array([0,0,1])
N_bits=1e2
a2=arange(0,2,1)
## Transmitter ##
bits1=ceil(len(a2)*rand(N_bits))
bits=a1[array(bits1,dtype=int)]
bits=array([0,0,0,0,0,0,0,0, bits])

I get an error on the last line:

Error: 
bits=array([0,0,0,0,0,0,0,0, bits])

ValueError: setting an array element with a sequence.
1
  • 2
    the line before it should raise an exception, since you don't define a1.. Commented Aug 14, 2013 at 20:15

1 Answer 1

5

You want to join the list with the array, so try

bits=concatenate(([0,0,0,0,0,0,0,0], bits))

where concatenate() is numpy.concatenate(). You can also use zeros(8, dtype=int) in place of the list of zeros (see numpy.zeros()).

Unlike in Matlab, something like [0,0,0,0,0,0,0,0, bits] in Python creates a list with the initial zeros follows by an embedded list.

Matlab:

>> x = [1,2,3]

x =

     1     2     3

>> [0,0,x]

ans =

     0     0     1     2     3

Python:

>>> x = [1,2,3]
>>>
>>> [0,0,x]
[0, 0, [1, 2, 3]]
>>> 
>>> [0,0] + x
[0, 0, 1, 2, 3]
4
  • Depending on how large 'bits' is you might want to preallocate an array of the appropriate size and then fill it like: bits = np.zeros(8 + N_bits, dtype='uint8'); bits[8:] = ... Commented Aug 14, 2013 at 20:18
  • @arshajii nope it doesnt work it says bits=array([0,0,0,0,0,0,0,0]+bits) ValueError: operands could not be broadcast together with shapes (8) (100) Commented Aug 14, 2013 at 20:20
  • 2
    numpy arrays overload the + operator to mean elementwise addition. To concatenate, use numpy.concatenate((array1, array2, ...)). Commented Aug 14, 2013 at 20:30
  • @StevenRumbalski Ack, of course. Must be coffee o'clock for me. Commented Aug 14, 2013 at 21:11

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.