Home > Commands > Numerical Math -> Arrays  (NumPy Object)


EXAMPLES ON MY SAGE PAGE - Sage Lists and Numpy Arrays


  • Arrays are created using NumPy (import numpy).
  • Arrays can be 1-dimensional or multi-dimensional.
  • For numbers, a 1-dimensional array (numpy) is like a 1-dimensional list (sage) except that an array works faster because the size is pre-allocated. This saves computer "checking" time. Also some commands are not available on sage lists.

To turn a Sage list list1 into a 1D NumPy array you must first do: import numpy (this makes numpy commands available in sage).

import numpy
array1=numpy.array (list1)


Here are some array creation functions.

Command Command Syntax   Example   Comment
array numpy.array(object [,dtype] ...)}}

numpy.array([1,2,3])   Creates a 1D array [ 1 2 3] with integer elements
      numpy.array([1.,2.,3.])   Creates a 1D array [ 1. 2. 3.] with decimal (float) elements
      numpy.array([1,2,3],dtype=float)   Creates a 1D array [ 1. 2. 3.] with decimal (float) elements
      numpy.array([j*j for j in range(10)])   Creates a 1D array with the first 10 squares starting with 0.
Result: [0 1 4 9 ...81]
 
An nx2 array
  A=numpy.array([[x1[j], 1] for j in range(n)])   Creates a 2D array with shape nx2. Notice the ordering is from outside-in. The n rows are the outside array for j in range(n), then the 2 columns are the inside array. Here x1 is a (previously defined) list or 1D array of length n and so A is a nx2 array with the elements of x1 in the first column and the number 1 everywhere in the second column.
arrange numpy.arange([start,] stop [, step,][, dtype])

    Return evenly spaced values within a given interval.
ones numpy.ones(shape [, dtype] ... )

    numpy.ones
zeros numpy.zeros(shape [, dtype] ... )

    numpy.zeros

Main SAGE Link: http://www.sagemath.org/doc/numerical_sage/
Main NumPy Link: http://docs.scipy.org/doc/numpy/reference/routines.array-creation.html


Keywords: arrays, numpy, lists, sage, shape, dtype, arrange, zeros, ones