1

I would like to figure out how i can create this array without putting every single value in per hand.

Is there a way how i can use the information that every value is the doubled value of its predecessor, except for the first?

My Code is as follows:


import numpy as np

Matrix = np.array([1,2,4,8,16,32,64,128,256]).reshape (3,3)

print(Matrix)

kmario23
  • 57,311
  • 13
  • 161
  • 150
R.K.
  • 13
  • 4
  • Maybe not more elegant, but a bitshift works in this case: `np.left_shift(1,np.arange(9)).reshape(3,3)` – Brenlla May 09 '19 at 17:04

4 Answers4

5

You can use np.arange, and take advantage of the fact that they are powers of 2:

2**np.arange(9).reshape(-1, 3)

array([[  1,   2,   4],
       [  8,  16,  32],
       [ 64, 128, 256]], dtype=int32)
yatu
  • 86,083
  • 12
  • 84
  • 139
1

You could also do something like this:

var myRandomArray = [1];
var i = 1;
var num = 1;
while (i < 9) {
  myRandomArray.push(num = num * 2);
  i = i + 1;
}

This is written in JavaScript. For Python, just switch what you need around, the main idea is still there. I believe in Python, it is append instead of push.

rowlandev
  • 37
  • 7
  • OP is looking for a python solution, as clear with the tags of the question – yatu May 09 '19 at 15:59
  • gave him a javascript solution, the main idea is the solution of the problem as a python programmer will know what the syntax is – rowlandev May 09 '19 at 16:06
1

You could use np.vander:

np.vander([2], 9, True).reshape(3, 3)
# array([[  1,   2,   4],
#        [  8,  16,  32],
#        [ 64, 128, 256]])
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
0

Here's a jury-rigged solution:

In [10]: total_num = 9 

In [11]: np.array([2**n for n in range(0, total_num)]).reshape(3, -1) 
Out[11]: 
array([[  1,   2,   4],
       [  8,  16,  32],
       [ 64, 128, 256]])
kmario23
  • 57,311
  • 13
  • 161
  • 150