I am a MATLAB user. What is the easiest way to port the following MATLAB script to python
a = []
for i=1:10
for j=1:10
a(i,j) = i*j
end
end
Look at the display when you run the MATLAB
a = 1
a =
1 2
a =
1 2 3
a =
1 2 3 4
.... (so on for 100 iterations)
In Octave I can do:
>> i=1:10
i =
1 2 3 4 5 6 7 8 9 10
>> j=(1:10)'
j =
1
2
3
4
5
6
7
8
9
10
>> a=i+j
a =
2 3 4 5 6 7 8 9 10 11
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12 13
5 6 7 8 9 10 11 12 13 14
6 7 8 9 10 11 12 13 14 15
7 8 9 10 11 12 13 14 15 16
8 9 10 11 12 13 14 15 16 17
9 10 11 12 13 14 15 16 17 18
10 11 12 13 14 15 16 17 18 19
11 12 13 14 15 16 17 18 19 20
This makes use of broadcasting, a concept borrowed from numpy
In [500]: i=np.arange(1,11)
In [501]: a = i[:,None] + i
In [502]: a
Out[502]:
array([[ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
[ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
[ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
[ 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
[ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]])
This is best practice - in numpy and I dare say MATLAB and Octave.
But if you must use iteration do something like
In [503]: a=np.zeros((10,10),int)
In [504]: for i in range(10):
...: for j in range(10):
...: a[i,j]=i+j
Or with full blown python list iteration:
In [512]: alist = []
In [513]: for i in range(10):
...: sublist=[]
...: for j in range(10):
...: sublist.append(i+j)
...: alist.append(sublist)
...:
In [514]: alist
Out[514]:
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
[9, 10, 11, 12, 13, 14, 15, 16, 17, 18]]
In [515]: np.array(alist)
Out[515]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
[ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
[ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
[ 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
[ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]])
but I can generate alist
more compactly with
alist=[[i+j for i in range(10)] for j in range(10)]
When you build a list of lists, make sure the sublists all have the same length - or else you'll come back to SO with question.