Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple adding two arrays using numpy in python?

This might be a simple question. However, I wanted to get some clarifications of how the following code works.

a = np.arange(8)
a
array([1,2,3,4,5,6,7])
Example Function = a[0:-1]+a[1:]/2.0

In the Example Function, I want to draw your attention to the plus sign between the array a[0:-1]+a[1:]. How does that work? What does that look like?

For instance, is the plus sign (addition) adding the first index of each array? (e.g 1+2) or add everything together? (e.g 1+2+2+3+3+4+4+5+5+6+6+7)

Then, I assume /2.0 is just dividing it by 2...

like image 412
Seoyeon Hong Avatar asked Dec 04 '16 06:12

Seoyeon Hong


1 Answers

A numpy array uses vector algebra in that you can only add two arrays if they have the same dimensions as you are adding element by element

 a = [1,2,3,4,5]
 b = [1,1,1]
 a+b # will throw an error

whilst

 a = [1,2,3,4,5]
 b = [1,1,1,1,1]
 a+b # is ok

The division is also element by element.

Now to your question about the indexing

 a      = [1,2,3,4,5]
 a[0:-1]= [1,2,3,4]
 a[1:]  = [2,3,4,5]

or more generally a[index_start: index_end] is inclusive at the start_index but exclusive at the end_index - unless you are given a a[start_index:]where it includes everything up to and including the last element.

My final tip is just to try and play around with the structures - there is no harm in trying different things, the computer will not explode with a wrong value here or there. Unless you trying to do so of course.

like image 107
Chinny84 Avatar answered Oct 21 '22 05:10

Chinny84