This repository has been archived on 2021-05-17. You can view files and clone it, but cannot push or open issues or pull requests.
scientificComputing/resources/python/tutorial/03numpy.py

73 lines
1.8 KiB
Python

# first step: import numpy
# there are different ways to do so
# import numpy --> everything has to be access via e.g. numpy.cos(x)
# import numpy as np --> name numpy np, which means that everything can be accessed via e.g. np.cos(x)
# from numpy import cos, sin --> only import cosine and sine
# from numpy import cos as cosine --> only import cos and name it cosine
# from numpy import * --> import everything.
# for the moment, we use option 5
from numpy import *
# numpy uses arrays which can be though of as lists with a single datatype
# they can be initialized form a list
a = array([1.,2.,3.])
b = array([[1,2],[4,5.]])
print a
# in numpy many commands have the same name as in matlab. For example
# for creating base points for plotting, you can use
x = linspace(-2.,2.,9) # creates an array with 1000 points between -2 and 2
# arithmetic operation are elementwise, double asterics is power
y = 2*x + 2
y = x+x
y = x**2. - 1.
# matplotlib implements many functions, such as matlab
y = cos(x)
y = exp(x)
print y
# just like matlab, numpy arrays support logical indexing
xp = x[x > 0]
yp = log(xp) # example
xp = x[x > 0]
inx=where(x>0)
print inx
print x[inx]
# arrays can also be two dimensional
x = zeros( (3,2) ) # zeros takes a tuple
print x
x[2,1] = 1.
print x
print x > 0
print x[x > 0]
# other useful functions to generate arrays
x = random.randn(4,3) # unfortunately, the size specification is implemented inconsistently
x = ones( (3,3) )
# another very useful feature is this
x = random.randn(3,1) # column vector
y = random.randn(1,4) # row vector
print x
print y
print x+y # result is a matrix
print x/y
# works also with 2d arrays and vectors
x = random.randn(3,1) # column vector
z = random.randn(1,4) # row vector
y = random.randn(3,4) # 2d array
print y-x # columnwise subtraction
print y-z # rowwise subtraction