|
|
|
mat, fmat, cx_mat cx_fmat, umat, imat | dense matrix classes | |
cube, fcube, cx_cube cx_fcube, ucube, icube | dense cube class ("3D matrix") | |
operators | + − * @ / == != <= >= < > && || |
attributes | .n_rows, .n_cols, .n_elem, .n_slices, ... | |
element access | element/object access via (), [] and .at() | |
element initialisation | set elements via initialiser lists | |
.zeros | set all elements to zero | |
.ones | set all elements to one | |
.eye | set elements along main diagonal to one and off-diagonal elements to zero | |
.randu / .randn | set all elements to random values | |
.fill | set all elements to specified value | |
.imbue | imbue (fill) with values provided by functor or lambda function | |
.clean | replace elements below a threshold with zeros | |
.replace | replace specific elements with a new value | |
.transform | transform each element via functor or lambda function | |
.for_each | apply a functor or lambda function to each element | |
.set_size | change size without keeping elements (fast) | |
.reshape | change size while keeping elements | |
.resize | change size while keeping elements and preserving layout | |
.copy_size | change size to be same as given object | |
.reset | change size to empty | |
submatrix views | read/write access to contiguous and non-contiguous submatrices | |
subcube views | read/write access to contiguous and non-contiguous subcubes | |
[diag] | read/write access to matrix diagonals | |
.set_imag / .set_real | set imaginary/real part | |
.insert_rows/cols/slices | insert vector/matrix at specified row/column | |
.shed_rows/cols/slices | remove specified rows/columns | |
.swap_rows/cols | swap specified rows or columns | |
.swap | swap contents with given object | |
iterators (matrices) | iterators and associated member functions for dense matrices and vectors | |
iterators (cubes) | iterators and associated member functions for cubes | |
iterators (submatrices) | iterators and associated member functions for submatrices | |
.as_col / .as_row | return flattened matrix as column or row vector | |
.t / .st | return matrix transpose | |
.i | return inverse of square matrix | |
.min / .max | return extremum value | |
.index_min / .index_max | return index of extremum value | |
.eval | force evaluation of delayed expression | |
.in_range | check whether given location or span is valid | |
.is_empty | check whether object is empty | |
.is_vec | check whether matrix is a vector | |
.is_sorted | check whether vector or matrix is sorted | |
.is_trimatu / .is_trimatl | check whether matrix is upper/lower triangular | |
.is_diagmat | check whether matrix is diagonal | |
.is_square | check whether matrix is square sized | |
.is_symmetric | check whether matrix is symmetric | |
.is_hermitian | check whether matrix is hermitian | |
.is_sympd | check whether matrix is symmetric/hermitian positive definite | |
.is_zero | check whether all elements are zero | |
.is_finite | check whether all elements are finite | |
.has_inf | check whether any element is +-Inf | |
.has_nan | check whether any element is NaN | |
print object | ||
.brief_print | print object in abridged form | |
.save/.load (matrices and cubes) | save/load matrices and cubes in files |
linspace | generate vector with linearly spaced elements | |
logspace | generate vector with logarithmically spaced elements | |
regspace | generate vector with regularly spaced elements | |
randperm | generate vector with random permutation of a sequence of integers | |
eye | generate identity matrix | |
ones | generate object filled with ones | |
zeros | generate object filled with zeros | |
randu / randn | generate object with random values (uniform and normal distributions) | |
randg | generate object with random values (gamma distribution) | |
randi | generate object with random integer values in specified interval | |
toeplitz | generate Toeplitz matrix |
abs | obtain magnitude of each element | |
accu | accumulate (sum) all elements | |
affmul | affine matrix multiplication | |
all | check whether all elements are non-zero, or satisfy a relational condition | |
any | check whether any element is non-zero, or satisfies a relational condition | |
approx_equal | approximate equality | |
arg | phase angle of each element | |
as_scalar | convert 1x1 matrix to pure scalar | |
clamp | obtain clamped elements according to given limits | |
cond | condition number of matrix | |
conj | obtain complex conjugate of each element | |
cross | cross product | |
cumsum | cumulative sum | |
cumprod | cumulative product | |
det | determinant | |
diagmat | generate diagonal matrix from given matrix or vector | |
diagvec | extract specified diagonal | |
diff | differences between adjacent elements | |
dot / cdot / norm_dot | dot product | |
eps | obtain distance of each element to next largest floating point representation | |
expmat | matrix exponential | |
expmat_sym | matrix exponential of symmetric matrix | |
find | find indices of non-zero elements, or elements satisfying a relational condition | |
find_finite | find indices of finite elements | |
find_nonfinite | find indices of non-finite elements | |
find_unique | find indices of unique elements | |
fliplr / flipud | flip matrix left to right or upside down | |
imag / real | extract imaginary/real part | |
ind2sub | convert linear index to subscripts | |
index_min / index_max | indices of extremum values | |
inplace_trans | in-place transpose | |
intersect | find common elements in two vectors/matrices | |
join_rows / join_cols | concatenation of matrices | |
join_slices | concatenation of cubes | |
kron | Kronecker tensor product | |
log_det | log determinant | |
logmat | matrix logarithm | |
logmat_sympd | matrix logarithm of symmetric matrix | |
min / max | return extremum values | |
nonzeros | return non-zero values | |
norm | various norms of vectors and matrices | |
normalise | normalise vectors to unit p-norm | |
prod | product of elements | |
powmat | matrix power | |
rank | rank of matrix | |
rcond | reciprocal of condition number | |
repelem | replicate elements | |
repmat | replicate matrix in block-like fashion | |
reshape | change size while keeping elements | |
resize | change size while keeping elements and preserving layout | |
reverse | reverse order of elements | |
roots | roots of polynomial | |
shift | shift elements | |
shuffle | randomly shuffle elements | |
size | obtain dimensions of given object | |
sort | sort elements | |
sort_index | vector describing sorted order of elements | |
sqrtmat | square root of matrix | |
sqrtmat_sympd | square root of symmetric matrix | |
sum | sum of elements | |
sub2ind | convert subscripts to linear index | |
symmatu / symmatl | generate symmetric matrix from given matrix | |
trace | sum of diagonal elements | |
trans | transpose of matrix | |
trapz | trapezoidal numerical integration | |
trimatu / trimatl | copy upper/lower triangular part | |
trimatu_ind / trimatl_ind | obtain indices of upper/lower triangular part | |
unique | return unique elements | |
vectorise | flatten matrix into vector | |
misc functions | miscellaneous element-wise functions: exp, log, pow, sqrt, round, sign, ... | |
trig functions | trigonometric element-wise functions: cos, sin, ... |
chol | Cholesky decomposition | |
eig_sym | eigen decomposition of dense symmetric/hermitian matrix | |
eig_gen | eigen decomposition of dense general square matrix | |
eig_pair | eigen decomposition for pair of general dense square matrices | |
hess | upper Hessenberg decomposition | |
inv | inverse of general square matrix | |
inv_sympd | inverse of symmetric positive definite matrix | |
lu | lower-upper decomposition | |
null | orthonormal basis of null space | |
orth | orthonormal basis of range space | |
pinv | pseudo-inverse | |
qr | QR decomposition | |
qr_econ | economical QR decomposition | |
qz | generalised Schur decomposition | |
schur | Schur decomposition | |
solve | solve systems of linear equations | |
svd | singular value decomposition | |
svd_econ | economical singular value decomposition | |
syl | Sylvester equation solver |
conv | 1D convolution | |
conv2 | 2D convolution | |
fft / ifft | 1D fast Fourier transform and its inverse | |
fft2 / ifft2 | 2D fast Fourier transform and its inverse | |
interp1 | 1D interpolation | |
interp2 | 2D interpolation | |
polyfit | find polynomial coefficients for data fitting | |
polyval | evaluate polynomial |
stats functions | mean, median, standard deviation, variance | |
cov | covariance | |
cor | correlation | |
hist | histogram of counts | |
histc | histogram of counts with user specified edges | |
quantile | quantiles of a dataset | |
princomp | principal component analysis (PCA) | |
normpdf | probability density function of normal distribution | |
log_normpdf | logarithm version of probability density function of normal distribution | |
normcdf | cumulative distribution function of normal distribution | |
mvnrnd | random vectors from multivariate normal distribution | |
chi2rnd | random numbers from chi-squared distribution | |
wishrnd | random matrix from Wishart distribution | |
iwishrnd | random matrix from inverse Wishart distribution | |
running_stat | running statistics of scalars (one dimensional process/signal) | |
running_stat_vec | running statistics of vectors (multi-dimensional process/signal) | |
kmeans | cluster data into disjoint sets |
constants | pi, inf, NaN, speed of light, ... | |
wall_clock | timer for measuring number of elapsed seconds | |
libraries | list of external libraries used by PyArmadillo | |
Matlab/PyArmadillo syntax differences | examples of Matlab syntax and conceptually corresponding PyArmadillo syntax | |
example program | short example program | |
API additions | API stability and list of API additions |
mat
|
= |
matrix containing double-precision floating point elements
|
fmat
|
= |
matrix containing single-precision floating point elements
|
cx_mat
|
= |
matrix containing complex double-precision floating point elements
|
cx_fmat
|
= |
matrix containing complex single-precision floating point elements
|
umat
|
= |
matrix containing unsigned integers
|
imat
|
= |
matrix containing signed integers
|
mat() | ||
mat(n_rows, n_cols) | (elements are initialised to zero) | |
mat(n_rows, n_cols, fill_type) | (elements are initialised) | |
mat(list) | (treated as a column vector) | |
mat(list of lists) | ||
mat(str) | ||
cx_mat(mat,mat) | (for constructing a complex matrix out of two real matrices) | |
mat(NumPy array) | (converts a NumPy array of the same type into a PyArmadillo matrix) | |
mat(submatrix/diagonal view) | (explicitly copies a submatrix/diagonal view into a matrix) | |
mat(matrix) | (converts matrices of one type to another) |
fill.zeros | = | set all elements to 0 |
fill.ones | = | set all elements to 1 |
fill.eye | = | set the elements along the main diagonal to 1 and off-diagonal elements to 0 |
fill.randu | = | set each element to a random value from a uniform distribution in the [0,1] interval |
fill.randn | = | set each element to a random value from a normal/Gaussian distribution with zero mean and unit variance |
fill.none | = | do not initialise the elements |
"1 0; 0 1"
.
numpy.array(mat)
matplotlib
through conversion to a NumPy array
A = mat(5, 5, fill.randu) # initialise 5x5 matrix with uniformly distributed random values x = A[1,2] # get element in row 1, column 2 (indices from 0) M = umat(5, 5, fill.ones) # initialise unsigned integer matrix with ones N = mat(M) # convert to double-precision floating point B = A + A # addition C = A * B # matrix multiplication D = A @ B # element-wise multiplication X = cx_mat(A,B) # initialise complex matrix with A as real, B as imaginary B.zeros() # fill B with zeros B.set_size(10,10) # set size of B without preserving data B.ones(5,6) # set size of B to 5x5, fill with ones B.print("B:") # print B with "B:" as header
cube
|
= |
cube containing double-precision floating point elements
|
fcube
|
= |
cube containing single-precision floating point elements
|
cx_cube
|
= |
cube containing complex double-precision floating point elements
|
cx_fcube
|
= |
cube containing complex single-precision floating point elements
|
ucube
|
= |
cube containing unsigned integers
|
icube
|
= |
cube containing signed integers
|
cube() | ||
cube(n_rows, n_cols, n_slices) | (elements are initialised to zero) | |
cube(n_rows, n_cols, n_slices, fill_type) | (elements are initialised) | |
cube(list of lists of lists) | ||
cx_cube(cube,cube) | (for constructing a complex cube out of two real cubes) | |
cube(NumPy array) | (converts a NumPy array of the same type into a PyArmadillo cube) | |
cube(subcube view) | (explicitly copies a subcube view into a cube) | |
cube(cube) | (converts cubes of one type to another) |
fill.zeros | = | set all elements to 0 |
fill.ones | = | set all elements to 1 |
fill.randu | = | set each element to a random value from a uniform distribution in the [0,1] interval |
fill.randn | = | set each element to a random value from a normal/Gaussian distribution with zero mean and unit variance |
fill.none | = | do not initialise the elements |
numpy.array(cube)
A = cube(5, 5, 5, fill.randu) # initialise 5x5x5 cube with uniformly distributed random values x = A[1,2,3] # get element in row 1, column 2, slice 3 (indices from 0) Q = ucube(5, 5, 5, fill.ones) # initialise unsigned integer cube with ones R = cube(Q) # convert to double-precision floating point B = A + A # addition C = 2 * B # scalar multiplication D = A @ B # element-wise multiplication X = cx_cube(A,B) # initialise complex cube with A as real, B as imaginary B.zeros() # fill B with zeros B.set_size(10,10,10) # set size of B without preserving data B.ones(5,6,7) # set size of B to 5x6x7, fill with ones B.print("B:") # print B with "B:" as header
+ − * @ / == != <= >= < > && ||
==
, !=
, >=
, <=
, >
, <
, &&
, ||
)
each element in the generated object is either 0 or 1, depending on the result of the operation
==
, !=
, >=
, <=
)
are not recommended for matrices of type mat, due to the necessarily limited precision of the underlying element types;
consider using approx_equal() instead
A = mat(5, 10, fill.randu) B = mat(5, 10, fill.randu) C = mat(10, 5, fill.randu) P = A + B # addition Q = A - B # subtraction R = -B # negation S = A / 123.0 # element-wise division by a scalar T = A @ B # element-wise multiplication U = A * C # matrix multiplication AA = umat("1 2 3; 4 5 6; 7 8 9;") BB = umat("3 2 1; 6 5 4; 9 8 7;") # compare elements ZZ = (AA >= BB) # broadcasting X = mat(6, 5, fill.ones) v = mat(6, 1, fill.randu) # in-place addition of v to each column vector of X X += v # generate Y by adding v to each column vector of X Y = X + v
.n_rows
|
number of rows; present in mat and cube | |
.n_cols
|
number of columns; present in mat and cube | |
.n_slices
|
number of slices; present in cube | |
.n_elem
|
total number of elements; present in mat and cube |
X = mat(4,5) print("X has " + str(X.n_cols) + " columns") Y = cube(4,5,6) print("Y has " + str(Y.n_slices) + " slices")
[n]
|
|
For mat and cube classes, access the n-th element/object under the assumption of a flat layout, with column-major ordering of data (i.e. column by column). A RuntimeError is thrown if the requested element is out of bounds. |
[i,j]
|
For mat class, access the element/object stored at the i-th row and j-th column. A RuntimeError is thrown if the requested element is out of bounds. | |
[i,j,k]
|
For cube class, access the element/object stored at the i-th row, j-th column and k-th slice. A RuntimeError is thrown if the requested element is out of bounds. |
A = mat(10, 10, fill.randu) A[9,9] = 123.0 # set element in row 9, column 9 to 123.0 x = A[9,9] # get element in row 9, column 9 y = A[99] # get 99th element A = cube(10, 10, 10, fill.randu) A[9,9,9] = 123.0 # set element in row 9, column 9, slice 9 to 123.0 x = A[9,9,9] # get element in row 9, column 9, slice 9 y = A[99] # get 99th element
A = mat([ [1, 3, 5], [2, 4, 6] ]) Q = cube([ [ [ 1, 3 , 5 ], [ 2, 4 , 6 ] ], [ [ 7, 9 , 11 ], [ 8, 10, 12 ] ] ])
.zeros() | ||
.zeros( n_rows, n_cols ) | ||
.zeros( size(X) ) |
A = mat(5,10) A.zeros() # or: A = mat(5,10,fill.zeros) B = mat() B.zeros(10,20) C = mat() C.zeros( size(B) )
.ones() | |
.ones( n_rows, n_cols ) | |
.ones( size(X) ) |
A = mat(5,10) A.ones() # or: A = mat(5,10,fill.ones) B = mat() B.ones(10,20) C = mat() C.ones( size(B) )
A = mat(5,5) A.eye() # or: A = mat(5,5,fill.eye) B = mat() B.eye(5,5) C = mat() C.eye( size(B) )
.randu() | |||
.randu( n_rows, n_cols ) | (member function of matrix) | ||
.randu( n_rows, n_cols, n_slice ) | (member function of cube) | ||
.randu( size(X) ) |
.randn() | |||
.randn( n_rows, n_cols ) | (member function of matrix) | ||
.randn( size(X) ) | (member function of cube) |
A = mat(5,10) A.randu() # or: A = mat(5,10,fill.randu) B = mat() B.randu(10,20) C = mat() C.randu( size(B) ) pyarma_rng.set_seed_random() # set the seed to a random value
A = mat(5, 6) A.fill(123.0)
A = mat(5, 6, fill.zeros)
from random import uniform A = mat(4, 5) A.imbue( lambda: uniform(0, 1) )
A = mat() A.randu(1000, 1000) A[12,34] = datum.eps A[56,78] = -datum.eps A.clean(datum.eps)
A = mat(5, 6, fill.randu) A[diag].fill(datum.nan) A.replace(datum.nan, 0) # replace each NaN with 0
A = mat(4, 5, fill.ones) # add 123 to every element A.transform( lambda val: val + 123.0 )
# print each element in a dense matrix A = mat(4, 5, fill.ones) A.for_each( lambda val: print(val) )
.set_size( n_rows, n_cols ) | (member function of matrix) | ||
.set_size( n_rows, n_cols, n_slices ) | (member function of cube) | ||
.set_size( size(X) ) |
A = mat() A.set_size(5,10) # or: A = mat(5,10) B = mat() B.set_size( size(A) ) # or: B = mat( size(A) )
.reshape( n_rows, n_cols ) | (member function of matrix) | ||
.reshape( n_rows, n_cols, n_slices ) | (member function of cube) | ||
.reshape( size(X) ) |
A = mat(4, 5, fill.randu) A.reshape(5,4)
.resize( n_rows, n_cols ) | (member function of matrix) | ||
.resize( size(X) ) | (member function of cube) |
A = mat(4, 5, fill.randu) A.resize(7,6)
A = mat(5, 6, fill.randu) B = mat() B.copy_size(A) print(str(B.n_rows)) print(str(B.n_cols))
A = mat(5, 5, fill.randu) A.reset()
|
|
A = mat(5, 10, fill.zeros) # set submatrix of rows 0-2 and columns 1-3 to uniformly distributed random elements A[ 0:2, 1:3 ] = mat(3,3, fill.randu) A[ 0,1, size(3,3) ] = mat(3,3, fill.randu) # copy submatrix of rows 0-2 and columns 1-3 B = A[ 0:2, 1:3 ].eval() D = A[ 0, 1, size(3,3) ].eval() # set column 1 to uniformly distributed random elements A[:,1] = mat(5,1,fill.randu) X = mat(5, 5, fill.randu) # get all elements of X that are greater than 0.5 q = X[ find(X > 0.5) ] # add 123 to all elements of X greater than 0.5 X[ find(X > 0.5) ] += 123.0 # set four specific elements of X to 1 indices = umat([ 2, 3, 6, 8 ]) X[indices] = mat(4,1,fill.ones)
Q[ first_row, first_col, first_slice, size(n_rows, n_cols, n_slices) ] Q[ first_row, first_col, first_slice, size(R) ] [ R is a cube ] Q[ first_row, first_col, last_row, last_col ] Q[ first_row : last_row, first_col : last_col ] Q[ first_row, first_col, size(n_rows, n_cols) ] |
|
A = cube(2, 3, 4, fill.randu) B = A[single_slice, 1] # the slice is accessed as a matrix A[:,:,0] = mat(2,3,fill.randu) A[:,:,0][1,2] = 99.0 A[ 0:1, 0:1, 1:2 ] = cube(2,2,2,fill.randu) A[ 0, 0, 1, size(2,2,2) ] = cube(2,2,2,fill.randu) # add 123 to all elements of A greater than 0.5 A[ find(A > 0.5) ] += 123.0 C = A[head_slices,2] # get first two slices A[head_slices, 2] += 123.0
X = mat(5, 5, fill.randu) a = X[diag].eval() # copy main diagonal b = X[diag, 1].eval() # copy first super-diagonal c = X[diag, -2].eval() # copy second sub-diagonal X[diag] = mat(5,1,fill.randu) # set main diagonal to uniformly distributed random elements X[diag] += 6 # add 6 to all main diagonal elements X[diag].ones() # set all main diagonal elements to one
A = mat(4, 5, fill.randu) B = mat(4, 5, fill.randu) C = cx_mat(4, 5, fill.zeros) C.set_real(A) C.set_imag(B)
A = mat(4, 5, fill.randu) B = mat(4, 5, fill.randu) C = cx_mat(A,B)
.insert_rows( row_number, X )
.insert_rows( row_number, number_of_rows ) .insert_rows( row_number, number_of_rows, set_to_zero ) |
||
.insert_cols( col_number, X )
.insert_cols( col_number, number_of_cols ) .insert_cols( col_number, number_of_cols, set_to_zero ) |
||
.insert_slices( slice_number, X )
.insert_slices( slice_number, number_of_slices ) .insert_slices( slice_number, number_of_slices, set_to_zero ) |
(member functions of cube) | |
A = mat(5, 10, fill.randu) B = mat(5, 2, fill.ones ) # at column 2, insert a copy of B; # A will now have 12 columns A.insert_cols(2, B) # at column 1, insert 5 zeroed columns; # B will now have 7 columns B.insert_cols(1, 5)
.shed_row( row_number )
.shed_rows( first_row, last_row ) .shed_rows( vector_of_indices ) |
||
.shed_col( column_number )
.shed_cols( first_column, last_column ) .shed_cols( vector_of_indices ) |
||
.shed_slices( slice_number )
.shed_slices( first_slice, last_slice ) .shed_slices( vector_of_indices ) |
(member functions of cube) |
A = mat(5, 10, fill.randu) B = mat(5, 10, fill.randu) A.shed_row(2) A.shed_cols(2,4) indices = umat([4, 6, 8]) B.shed_cols(indices)
X = mat(5, 5, fill.randu) X.swap_rows(0,4)
A = mat(4, 5, fill.zeros) B = mat(6, 7, fill.ones ) A.swap(B)
iter( X ) | |
iterator from the first to last element |
iterator( X, i, j ) | |
iterator from the i-th element to the j-th element |
col_iter( X, i, j ) | |
iterator from the first element of the i-th column to the last element of the j-th column |
row_iter( X, i, j ) | |
iterator from the first element of the i-th row to the last element of the j-th row |
X = mat(5, 6, fill.randu) for i in X: # this prints all elements print(i) it = iter(X) # this also prints all elements for i in it: print(i) col_it = col_iter(X, 1, 3) # start of column 1 and end of column 3 for i in col_it: # print all elements of columns 1-3 print(i)
iter( Q ) | |
iterator from the first to last element |
iterator( Q, i, j ) | |
iterator from the i-th element to the j-th element |
slice_iter( Q, i, j ) | |
iterator from the first element of the i-th slice to the last element of the j-th slice |
X = cube(5, 6, 7, fill.randu) for i in X: # this prints all elements print(i) it = iter(X) # this also prints all elements for i in it: print(i) slice_it = slice_iter(X, 1, 3) # start of slice 1 and end of cslice 3 for i in slice_it: # print all elements of slices 1-3 print(i)
X = mat(100, 200, fill.randu) for val in X[40:60, 50:100]: print(val)
X = mat(4, 5, fill.randu) v = X.as_col()
A = mat(4, 5, fill.randu) B = A.t()
A = mat(4, 4, fill.randu) X = A.i() Y = (A+A).i()
A = mat(5, 5, fill.randu) max_val = A.max()
A = mat(5, 5, fill.randu) i = A.index_max() max_val = A[i]
A = umat(4,4,fill.ones) B = A[0:1, 2:3].eval() # any change to B does not affect A B[0,0] = 5 # therefore, B and A[0:1, 2:3] are not equal (B == A[0:1, 2:3]).print()
.in_range( i ) | |||
.in_range( start : end ) | |||
.in_range( row, col ) | (member of mat) | ||
.in_range( start_row : end_row, start_col : end_col ) | (member of mat) | ||
.in_range( row, col , slice) | (member of cube) | ||
.in_range( start_row : end_row, start_col : end_col, start_slice: end_slice ) | (member of cube) | ||
.in_range( first_row, first_col, size(X) ) (X is a matrix) | (member of mat) | ||
.in_range( first_row, first_col, size(n_rows, n_cols) ) | (member of mat) | ||
.in_range( first_row, first_col, first_slice, size(Q) ) (Q is a cube) | (member of cube) | ||
.in_range( first_row, first_col, first_slice, size(n_rows, n_cols, n_slices) ) | (member of cube) |
A = mat(4, 5, fill.randu) print(A.in_range(0,0)) # True print(A.in_range(3,4)) # True print(A.in_range(4,5)) # False
A = mat(5, 5, fill.randu) print(A.is_empty()) A.reset() print(A.is_empty())
A = mat(1, 5, fill.randu) B = mat(5, 1, fill.randu) C = mat(5, 5, fill.randu) print(A.is_vec()) print(B.is_vec()) print(C.is_vec())
.is_sorted() | (form 1) | |
.is_sorted( sort_direction ) | (form 2) | |
.is_sorted( sort_direction, dim ) | (form 3) |
"ascend" | ↦ | elements are ascending; consecutive elements can be equal; this is the default operation |
"descend" | ↦ | elements are descending; consecutive elements can be equal |
"strictascend" | ↦ | elements are strictly ascending; consecutive elements cannot be equal |
"strictdescend" | ↦ | elements are strictly descending; consecutive elements cannot be equal |
a = mat(10, 1, fill.randu) b = sort(a) check1 = a.is_sorted() check2 = b.is_sorted() A = mat(10, 10, fill.randu) # check whether each column is sorted in descending manner print(A.is_sorted("descend")) # check whether each row is sorted in ascending manner print(A.is_sorted("ascend", 1))
A = mat(5, 5, fill.randu) B = trimatl(A) print(A.is_trimatu()) print(B.is_trimatl())
A = mat(5, 5, fill.randu) B = diagmat(A) print(A.is_diagmat()) print(B.is_diagmat())
A = mat(5, 5, fill.randu) B = mat(6, 7, fill.randu) print(A.is_square()) print(B.is_square())
A = mat(5, 5, fill.randu) B = A.t() * A print(A.is_symmetric()) print(B.is_symmetric())
A = cx_mat(5, 5, fill.randu) B = A.t() * A print(A.is_hermitian()) print(B.is_hermitian())
A = mat(5, 5, fill.randu) B = A.t() * A print(A.is_sympd()) print(B.is_sympd())
A = mat(5, 5, fill.zeros) A[0,0] = datum.eps print(A.is_zero()) print(A.is_zero(datum.eps))
A = mat(5, 5, fill.randu) B = mat(5, 5, fill.randu) B[0,0] = datum.inf print(A.is_finite()) print(B.is_finite())
A = mat(5, 5, fill.randu) B = mat(5, 5, fill.randu) B[0,0] = datum.inf print(A.has_inf()) print(B.has_inf())
NaN
is not equal to anything, even itself
A = mat(5, 5, fill.randu) B = mat(5, 5, fill.randu) B[0,0] = datum.nan print(A.has_nan()) print(B.has_nan())
A = mat(5, 5, fill.randu) A.print() # "A:" is the optional header line A.print("A:") # print a transposed version of A A.t().print()
A = mat(123, 456, fill.randu) A.brief_print() # possible output: # # [matrix size: 123x456] # 0.8402 0.7605 0.6218 ... 0.9744 # 0.3944 0.9848 0.0409 ... 0.7799 # 0.7831 0.9350 0.4140 ... 0.8835 # : : : : : # 0.4954 0.1826 0.9848 ... 0.1918
.save( filename )
.save( filename, file_type ) |
.load( filename )
.load( filename, file_type ) |
auto_detect |
Used only by .load() only: attempt to automatically detect the file type as one of the formats described below;
[ default operation for .load() ] |
|
arma_binary |
Numerical data stored in machine dependent binary format, with a simple header to speed up loading.
The header indicates the type and size of matrix.
[ default operation for .save() ] |
|
arma_ascii |
Numerical data stored in human readable text format, with a simple header to speed up loading.
The header indicates the type and size of matrix.
|
|
raw_binary |
Numerical data stored in machine dependent raw binary format, without a header.
Matrices are loaded to have one column.
The .reshape() function can be used to alter the size of the loaded matrix without losing data.
|
|
raw_ascii |
Numerical data stored in raw ASCII format, without a header.
The numbers are separated by whitespace.
The number of columns must be the same in each row.
Data which was saved in Matlab/Octave using the -ascii option can be read in PyArmadillo, except for complex numbers.
Complex numbers are stored in standard C++ notation, which is a tuple surrounded by brackets: e.g. (1.23,4.56) indicates 1.24 + 4.56i.
|
|
csv_ascii |
Numerical data stored in comma separated value (CSV) text format, without a header.
Handles complex numbers stored in the compound form of 1.24+4.56i
|
|
pgm_binary |
Image data stored in Portable Gray Map (PGM) format.
Saving int, float or double matrices is a lossy operation, as each element is copied and converted to an 8 bit representation.
As such the matrix should have values in the [0,255] interval, otherwise the resulting image may not display correctly.
|
|
hdf5_binary |
Numerical data stored in portable HDF5 binary format.
|
A = mat(5, 6, fill.randu) # default save format is arma_binary A.save("A.bin") # save in raw_ascii format A.save("A.txt", raw_ascii) # save in CSV format without a header A.save("A.csv", csv_ascii) # save in HDF5 format A.save("A.h5", hdf5_binary) # automatically detect format type while loading B = mat() B.load("A.bin") # force loading in arma_ascii format C = mat() C.load("A.txt", arma_ascii) # example of testing for success D = mat() ok = D.load("A.bin") if not ok: print("problem with loading")
a = linspace(0, 5, 6)
a = logspace(0, 5, 6)
a = regspace(0, 9) # 0, 1, ..., 9 b = regspace(2, 2, 10) # 2, 4, ..., 10 c = regspace(0, -1, -10) # 0, -1, ..., -10
X = randperm(10) Y = randperm(10,2)
A = eye(5,5) // or: A = mat(5,5,fill.eye) B = 123.0 * eye(5,5) C = 123.0 * fmat(eye(5,5))
v = ones(10) u = umat(ones(11)) A = ones(5,6) Q = ones(5,6,7) B = 123.0 * ones(5,6)
v = zeros(10) u = umat(zeros(11)) A = zeros(5,6) Q = zeros(5,6,7)
v = randu(5) A = randu(5,6) Q = randu(5,6,7) pyarma_rng.set_seed_random() # set the seed to a random value
x a-1 exp( -x / b ) | ||
p(x|a,b) | = | |
b a Γ(a) |
v = randg(100, distr_param(2,1)) # generates a vector X = randg(10, 10, distr_param(2,1)) # generates a matrix
A = randi(5, 6) # generates a matrix A = randi(6, 7, distr_param(-10, +20)) # generates a matrix pyarma_rng.set_seed_random() # set the seed to a random value
A = mat(5, 1, fill.randu) X = toeplitz(A) Y = circ_toeplitz(A)
A = mat(5, 5, fill.randu) B = abs(A) X = cx_mat(5, 5, fill.randu) Y = abs(X)
A = mat(5, 6, fill.randu) B = mat(5, 6, fill.randu) x = accu(A) y = accu(A @ B) # accu(A @ B) is a "multiply-and-accumulate" operation # as operator @ performs element-wise multiplication
⎡ A00 A01 A02 ⎤ ⎡ B0 ⎤ ⎢ A10 A11 A12 ⎥ x ⎢ B1 ⎥ ⎣ A20 A21 A22 ⎦ ⎣ 1 ⎦
A = mat(4, 4, fill.randu) B = mat(3, 1, fill.randu) C = affmul(A,B)
all( X ) | (form 1) | |
all( X, dim ) | (form 2) |
V = mat(10,1, fill.randu) X = mat(5, 5, fill.randu) # status1 will contain 1 if vector V has all non-zero elements status1 = all(V) # status2 will contain 1 if vector V has all elements greater than 0.5 status2 = all(V > 0.5) # status3 will be contain 1 if matrix X has all elements greater than 0.6; # note the use of vectorise() status3 = all(vectorise(X) > 0.6) # generate a row vector indicating which columns of X have all elements greater than 0.7 uA = all(X > 0.7)
any( X ) | (form 1) | |
any( X, dim ) | (form 2) |
V = mat(10,1, fill.randu) X = mat(5, 5, fill.randu) # status1 will contain 1 if matrix V has any non-zero elements status1 = any(V) # status2 will contain 1 if matrix V has any elements greater than 0.5 status2 = any(V > 0.5) # status3 will contain 1 if matrix X has any elements greater than 0.6; # note the use of vectorise() status3 = any(vectorise(X) > 0.6) # generate a row vector indicating which columns of X have elements greater than 0.7 uA = any(X > 0.7)
"absdiff" | ↦ | scalars x and y are considered equal if |x − y| ≤ tol |
"reldiff" | ↦ | scalars x and y are considered equal if |x − y| / max( |x|, |y| ) ≤ tol |
"both" | ↦ | scalars x and y are considered equal if |x − y| ≤ abs_tol or |x − y| / max( |x|, |y| ) ≤ rel_tol |
A = mat(5, 5, fill.randu) B = A + 0.001 same1 = approx_equal(A, B, "absdiff", 0.002) C = 1000 * mat(5,5, fill.randu) D = C + 1 same2 = approx_equal(C, D, "reldiff", 0.1) same3 = approx_equal(C, D, "both", 2, 0.1)
A = cx_mat(5, 5, fill.randu) B = arg(A)
r = mat(1, 5, fill.randu) q = mat(5, 1, fill.randu) X = mat(5, 5, fill.randu) a = as_scalar(r*q) b = as_scalar(r*X*q) c = as_scalar(r*diagmat(X)*q) d = as_scalar(r*inv(diagmat(X))*q)
A = mat(5, 5, fill.randu ) B = clamp(A, 0.2, 0.8) C = clamp(A, A.min(), 0.8) D = clamp(A, 0.2, A.max())
A = mat(5, 5, fill.randu) c = cond(A)
X = cx_mat(5, 5, fill.randu) Y = conj(X)
a = mat(3, 1, fill.randu) b = mat(3, 1, fill.randu) c = cross(a,b)
cumsum( X ) | (form 1) | |
cumsum( X, dim ) | (form 2) |
A = mat(5, 5, fill.randu) B = cumsum(A) C = cumsum(A, 1) x = mat(10, 1, fill.randu) y = cumsum(x)
cumprod( X ) | (form 1) | |
cumprod( X, dim ) | (form 2) |
A = mat(5, 5, fill.randu) B = cumprod(A) C = cumprod(A, 1) x = mat(10, 1, fill.randu) y = cumprod(x)
A = mat(5, 5, fill.randu) x = det(A)
A = mat(5, 5, fill.randu) B = diagmat(A) C = diagmat(A,1) v = mat(5, 1, fill.randu) D = diagmat(v) E = diagmat(v,1)
A = mat(5, 5, fill.randu) d = diagvec(A)
diff( X ) | (form 1) | |
diff( X, k ) | (form 2) | |
diff( X, k, dim ) | (form 3) |
a = linspace(1,10,10) b = diff(a)
a = mat(10, 1, fill.randu) b = mat(10, 1, fill.randu) x = dot(a,b)
A = mat(4, 5, fill.randu) B = eps(A)
A = mat(5, 5, fill.randu) B = expmat(A)
A = mat(5, 5, fill.randu) B = A*A.t() # make symmetric matrix C = expmat_sym(B)
A = mat(5, 5, fill.randu) B = mat(5, 5, fill.randu) q1 = find(A > B) q2 = find(A > 0.5) q3 = find(A > 0.5, 3, "last") # change elements of A greater than 0.5 to 1 A[ find(A > 0.5) ].ones()
A = mat(5, 5, fill.randu) A[1,1] = datum.inf # accumulate only finite elements val = accu( A[ find_finite(A) ] )
A = mat(5, 5, fill.randu) A[1,1] = datum.inf A[2,2] = datum.nan # change non-finite elements to zero A[ find_nonfinite(A) ].zeros()
True | = | the returned indices are sorted to be ascending (default setting) |
False | = | the returned indices are in arbitrary order (faster operation) |
A = mat([ [ 2, 2, 4 ], [ 4, 6, 6 ] ]) indices = find_unique(A)
A = mat(5, 5, fill.randu) B = fliplr(A) C = flipud(A)
C = cx_mat(5, 5, fill.randu) A = imag(C) B = real(C)
ind2sub( size(X), index ) | (form 1) | |
ind2sub( size(X), vector_of_indices ) | (form 2) |
M = mat(4, 5, fill.randu) s = ind2sub( size(M), 6 ) print("row: " + str(s[0])) print("col: " + str(s[1])) indices = find(M > 0.5) t = ind2sub( size(M), indices ) Q = cube(2, 3, 4) u = ind2sub( size(Q), 8 ) print("row: " + str(s[0])) print("col: " + str(s[1])) print("slice: " + str(s[2]))
index_min( M )
index_min( M, dim ) index_min( Q ) index_min( Q, dim ) |
index_max( M )
index_max( M, dim ) index_max( Q ) index_max( Q, dim ) |
|
(form 1)
(form 2) |
v = mat(10, 1, fill.randu) i = index_max(v) max_val_in_v = v[i] M = mat(5, 6, fill.randu) ii = index_max(M) jj = index_max(M,1) max_val_in_col_2 = M[ ii[2], 2 ] max_val_in_row_4 = M[ 4, jj[4] ]
X = mat(4, 5, fill.randu) Y = mat(20000, 30000, fill.randu) inplace_trans(X) inplace_trans(Y)
C = intersect( A, B ) | (form 1) | |
intersect( C, iA, iB, A, B ) | (form 2) |
A = regspace(4, 1) # 4, 3, 2, 1 B = regspace(3, 6) # 3, 4, 5, 6 C = intersect(A,B) # 3, 4 CC = mat() iA = umat() iB = umat() intersect(CC, iA, iB, A, B)
join_rows( A, B )
join_rows( A, B, C ) join_rows( A, B, C, D ) join_cols( A, B ) join_cols( A, B, C ) join_cols( A, B, C, D ) |
join_horiz( A, B )
join_horiz( A, B, C ) join_horiz( A, B, C, D ) join_vert( A, B ) join_vert( A, B, C ) join_vert( A, B, C, D ) |
A = mat(4, 5, fill.randu) B = mat(4, 6, fill.randu) C = mat(6, 5, fill.randu) AB = join_rows(A,B) AC = join_cols(A,C)
C = cube(5, 10, 3, fill.randu) D = cube(5, 10, 4, fill.randu) E = join_slices(C,D) M = mat(10, 20, fill.randu) N = mat(10, 20, fill.randu) Q = join_slices(M,N) R = join_slices(Q,M) S = join_slices(M,Q)
A = mat(4, 5, fill.randu) B = mat(5, 4, fill.randu) K = kron(A,B)
result = log_det( A ) |
A = mat(5, 5, fill.randu) result = log_det(A)
A = mat(5, 5, fill.randu) B = logmat(A)
A = mat(5, 5, fill.randu) B = A*A.t() # make symmetric matrix C = logmat_sympd(B)
min( X )
min( X, dim ) min( A, B ) |
max( X )
max( X, dim ) max( A, B ) |
|
(form 1)
(form 2) (form 3) |
v = mat(10, 1, fill.randu) x = max(v) M = mat(10, 10, fill.randu) a = max(M) b = max(M,0) c = max(M,1) # element-wise maximum X = mat(5, 6, fill.randu) Y = mat(5, 6, fill.randu) Z = max(X,Y)
B = mat(100, 100, fill.eye) b = nonzeros(B)
"-inf"
, "inf"
, "fro"
"inf"
, "fro"
; the calculated norm is the induced norm (not entrywise norm)
"-inf"
is the minimum norm, "inf"
is the maximum norm, while "fro"
is the Frobenius norm
accu(X != 0)
q = mat(5, 1, fill.randu) x = norm(q, 2) y = norm(q, "inf")
normalise( X ) | (form 1) | |
normalise( X, p ) | (form 2) | |
normalise( X, p, dim ) | (form 3) |
A = mat(10, 1, fill.randu) B = normalise(A) C = normalise(A, 1) X = mat(5, 6, fill.randu) Y = normalise(X) Z = normalise(X, 2, 1)
prod( X ) | (form 1) | |
prod( X, p ) | (form 2) |
v = mat(10, 1, fill.randu) x = prod(v) M = mat(10, 10, fill.randu) a = prod(M) b = prod(M,0) c = prod(M,1)
A = mat(5, 5, fill.randu) B = powmat(A, 4) # integer exponent C = powmat(A, 4.56) # non-integer exponent
A = mat(4, 5, fill.randu) r = rank(A)
A = mat(5, 5, fill.randu) r = rcond(A)
n_rows | = | num_copies_per_row | * | A.n_rows |
n_cols | = | num_copies_per_col | * | A.n_cols |
A = mat(2, 3, fill.randu) B = repelem(A, 4, 5)
n_rows | = | num_copies_per_row | * | A.n_rows |
n_cols | = | num_copies_per_col | * | A.n_cols |
A = mat(2, 3, fill.randu) B = repmat(A, 4, 5)
A = mat(10, 5, fill.randu) B = reshape(A, 5, 10)
A = mat(4, 5, fill.randu) B = resize(A, 7, 6)
reverse( X ) | (form 1) | |
reverse( X, p ) | (form 2) |
v = mat(123, 1, fill.randu) y = reverse(v) A = mat(4, 5, fill.randu) B = reverse(A) C = reverse(A,1)
P = mat(5, 1, fill.randu) R = roots(P)
shift( X, N ) | (form 1) | |
shift( X, N, dim ) | (form 2) |
A = mat(4, 5, fill.randu) B = shift(A, -1) C = shift(A, +1)
shuffle( X, ) | (form 1) | |
shuffle( X, dim ) | (form 2) |
A = mat(4, 5, fill.randu) B = shuffle(A)
A = mat(5,6) B = mat(size(A), fill.zeros) C = mat() C.randu(size(A)) D = mat(10,20, fill.ones) D[3,4,size(C)] = C # access submatrix of E E = mat( size(A) + size(E) ) F = mat( size(A) * 2 ) print("size of A: " + str(size(A))) is_same_size = (size(A) == size(E))
sort( X ) | (form 1) | |
sort( X, sort_direction ) | (form 2) | |
sort( X, sort_direction, dim ) | (form 3) |
"ascend"
or "descend"
; by default "ascend"
is usedA = mat(10, 10, fill.randu) B = sort(A)
"ascend"
or "descend"
; by default "ascend"
is usedq = mat(10, 1, fill.randu) indices = sort_index(q)
A = mat(5, 5, fill.randu) B = sqrtmat(A)
A = mat(5, 5, fill.randu) B = A*A.t() # make symmetric matrix C = sqrtmat_sympd(B)
sum( X ) | (form 1) | |
sum( X, dim ) | (form 2) |
v = mat(10, 1, fill.randu) x = sum(v) M = mat(10, 10, fill.randu) a = sum(M) b = sum(M,0) c = sum(M,1) y = accu(M) # find the overall sum regardless of object type
index | = sub2ind( size(M), row, col ) | (M is a matrix) | |
indices | = sub2ind( size(M), matrix_of_subscripts ) | ||
index | = sub2ind( size(Q), row, col, slice) | (Q is a cube) | |
indices | = sub2ind( size(M), matrix_of_subscripts ) |
M = mat(4,5) Q = cube(4,5,6) i = sub2ind( size(M), 2, 3 ) j = sub2ind( size(Q), 2, 3, 4 )
A = mat(5, 5, fill.randu) B = symmatu(A) C = symmatl(A)
A = mat(5, 5, fill.randu) x = trace(A)
A = mat(5, 10, fill.randu) B = trans(A) C = A.t() # equivalent to trans(A), but more compact
X = linspace(0, datum.pi, 1000) Y = sin(X) Z = trapz(X,Y)
A = mat(5, 5, fill.randu) U = trimatu(A) L = trimatl(A) UU = trimatu(A, 1) # omit the main diagonal LL = trimatl(A, -1) # omit the main diagonal
A = mat(5, 5, fill.randu) upper_indices = trimatu_ind( size(A) ) lower_indices = trimatl_ind( size(A) ) # extract upper/lower triangle into vector upper_part = A[upper_indices] lower_part = A[lower_indices] # obtain indices without the main diagonal alt_upper_indices = trimatu_ind( size(A), 1) alt_lower_indices = trimatl_ind( size(A), -1)
X = mat([ [ 1, 2 ], [ 2, 3 ] ]) Y = unique(X)
X = mat(4, 5, fill.randu) v = vectorise(X)
exp | log | pow | floor | erf | tgamma | sign | ||||||
exp2 | log2 | square | ceil | erfc | lgamma | |||||||
exp10 | log10 | sqrt | round | |||||||||
expm1 | log1p | trunc | ||||||||||
trunc_exp | trunc_log |
exp(A)
|
base-e exponential: e x | |||||||||||||
exp2(A)
|
base-2 exponential: 2 x | |||||||||||||
exp10(A)
|
base-10 exponential: 10 x | |||||||||||||
expm1(A)
|
compute exp(A)-1 accurately for values of A close to zero (only for floating point elements)
|
|||||||||||||
trunc_exp(A)
|
base-e exponential, truncated to avoid infinity (only for floating point elements) | |||||||||||||
log(A)
|
natural log: loge x | |||||||||||||
log2(A)
|
base-2 log: log2 x | |||||||||||||
log10(A)
|
base-10 log: log10 x | |||||||||||||
log1p(A)
|
compute log(1+A) accurately for values of A close to zero (only for floating point elements)
|
|||||||||||||
trunc_log(A)
|
natural log, truncated to avoid ±infinity (only for floating point elements) | |||||||||||||
pow(A, p)
|
raise to the power of p: x p | |||||||||||||
square(A)
|
square: x 2 | |||||||||||||
sqrt(A)
|
square root: √x | |||||||||||||
floor(A)
|
largest integral value that is not greater than the input value | |||||||||||||
ceil(A)
|
smallest integral value that is not less than the input value | |||||||||||||
round(A)
|
round to nearest integer, with halfway cases rounded away from zero | |||||||||||||
trunc(A)
|
round to nearest integer, towards zero | |||||||||||||
erf(A)
|
error function (only for floating point elements) | |||||||||||||
erfc(A)
|
complementary error function (only for floating point elements) | |||||||||||||
tgamma(A)
|
gamma function (only for floating point elements) | |||||||||||||
lgamma(A)
|
natural log of the absolute value of gamma function (only for floating point elements) | |||||||||||||
sign(A)
|
signum function;
for each element a in A, the corresponding element b in B is:
|
A = mat(5, 5, fill.randu) B = exp(A)
X = mat(5, 5, fill.randu) Y = cos(X)
"upper"
or "lower"
, which specifies whether R is upper or lower triangular
X = mat(5, 5, fill.randu) Y = X.t()*X R1 = chol(Y) R2 = chol(Y, "lower")
# for matrices with real elements A = mat(50, 50, fill.randu) B = A.t()*A # generate a symmetric matrix eigval = mat() eigvec = mat() eig_sym(eigval, eigvec, B) # for matrices with complex elements C = cx_mat(50, 50, fill.randu) D = C.t()*C eigval2 = mat() eigvec2 = cx_mat() eig_sym(eigval2, eigvec2, D)
"balance" | ↦ | diagonally scale and permute X to improve conditioning of the eigenvalues |
"nobalance" | ↦ | do not balance X; this is the default operation |
A = mat(10, 10, fill.randu) eigval = cx_mat() eigvec = cx_mat() eig_gen(eigval, eigvec, A) eig_gen(eigval, eigvec, A, "balance")
A = mat(10, 10, fill.randu) B = mat(10, 10, fill.randu) eigval = cx_mat() eigvec = cx_mat() eig_pair(eigval, eigvec, A, B)
X = mat(20,20, fill.randu) U = mat() H = mat() hess(U, H, X)
A = mat(5, 5, fill.randu) B = inv(A)
A = mat(5, 5, fill.randu) B = A.t() * A C = inv_sympd(B)
A = mat(5, 5, fill.randu) L = mat() U = mat() P = mat() lu(L, U, P, A) B = P.t()*L*U
A = mat(5, 6, fill.randu) A[0,:].zeros() A[:,0].zeros() B = null(A)
A = mat(5, 6, fill.randu) B = orth(A)
A = mat(4, 5, fill.randu) B = pinv(A) # use default tolerance C = pinv(A, 0.01) # set tolerance to 0.01
Q, R = qr( X ) | (form 1) | |
qr( Q, R, X ) | ||
Q, R, P = qr( X, "vector" ) | (form 2) | |
qr( Q, R, P, X, "vector" ) | ||
Q, R, P = qr( X, "matrix" ) | (form 3) | |
qr( Q, R, P, X, "matrix" ) |
X = mat(5, 5, fill.randu) Q = mat() R = mat() qr(Q, R, X) P_vec = umat() P_mat = umat() qr(Q, R, P_vec, X, "vector") qr(Q, R, P_mat, X, "matrix")
X = mat(6, 5, fill.randu) Q = mat() R = mat() qr_econ(Q, R, X)
"none" | no ordering (default operation) | |
"lhp" | left-half-plane: eigenvalues with real part < 0 | |
"rhp" | right-half-plane: eigenvalues with real part > 0 | |
"iuc" | inside-unit-circle: eigenvalues with absolute value < 1 | |
"ouc" | outside-unit-circle: eigenvalues with absolute value > 1 |
A = mat(10, 10, fill.randu) B = mat(10, 10, fill.randu) AA = mat() BB = mat() Q = mat() Z = mat() qz(AA, BB, Q, Z, A, B)
X = mat(20,20, fill.randu) U = mat() S = mat() schur(U, S, X)
solve_opts.fast | fast mode: disable determining solution quality via rcond, disable iterative refinement, disable equilibration | |
solve_opts.refine | apply iterative refinement to improve solution quality (matrix A must be square) | |
solve_opts.equilibrate | equilibrate the system before solving (matrix A must be square) | |
solve_opts.likely_sympd | indicate that matrix A is likely symmetric/hermitian positive definite | |
solve_opts.allow_ugly | keep solutions of systems that are singular to working precision | |
solve_opts.no_approx | do not find approximate solutions for rank deficient systems | |
solve_opts.no_band | do not use specialised solver for band matrices or diagonal matrices | |
solve_opts.no_trimat | do not use specialised solver for triangular matrices | |
solve_opts.no_sympd | do not use specialised solver for symmetric/hermitian positive definite matrices |
+
operator; for example: solve_opts.fast + solve_opts.no_approx
solve_opts.fast
will speed up finding the solution, but for poorly conditioned systems the solution may have lower quality
solve_opts.likely_sympd
A = mat(5, 5, fill.randu) b = mat(5, 1, fill.randu) B = mat(5, 5, fill.randu) x1 = solve(A, b) x2 = mat() status = solve(x2, A, b) X1 = solve(A, B) X2 = solve(A, B, solve_opts.fast) # enable fast mode
X = mat(5, 5, fill.randu) U = mat() s = mat() V = mat() svd(U,s,V,X)
"both" | = | compute both left and right singular vectors (default operation) | |
"left" | = | compute only left singular vectors | |
"right" | = | compute only right singular vectors |
X = mat(4, 5, fill.randu) U = mat() s = mat() V = mat() svd_econ(U, s, V, X)
A = mat(5, 5, fill.randu) B = mat(5, 5, fill.randu) C = mat(5, 5, fill.randu) X1 = syl(A, B, C) X2 = mat() syl(X2, A, B, C)
"full" | = | return the full convolution (default setting), with the size equal to A.n_elem + B.n_elem - 1 |
"same" | = | return the central part of the convolution, with the same size as vector A |
A = mat(256, 1, fill.randu) B = mat(16, 1, fill.randu) C = conv(A, B) D = conv(A, B, "same")
"full" | = | return the full convolution (default setting), with the size equal to size(A) + size(B) - 1 |
"same" | = | return the central part of the convolution, with the same size as matrix A |
A = mat(256, 256, fill.randu) B = mat(16, 16, fill.randu) C = conv2(A, B) D = conv2(A, B, "same")
X = mat(100, 1, fill.randu) Y = fft(X, 128)
A = mat(100, 100, fill.randu) B = fft2(A) C = fft2(A, 128, 128)
"nearest" | = | interpolate using single nearest neighbour |
"linear" | = | linear interpolation between two nearest neighbours (default setting) |
"*nearest" | = | as per "nearest" , but faster by assuming that X and XI are monotonically increasing |
"*linear" | = | as per "linear" , but faster by assuming that X and XI are monotonically increasing |
x = linspace(0, 3, 20) y = square(x) xx = linspace(0, 3, 100) yy = mat() interp1(x, y, xx, yy) # use linear interpolation by default interp1(x, y, xx, yy, "*linear") # faster than "linear" interp1(x, y, xx, yy, "nearest")
"nearest" | = | interpolate using nearest neighbours |
"linear" | = | linear interpolation between nearest neighbours (default setting) |
Z = mat() Z.load("input_image.pgm", pgm_binary) # load an image in pgm format X = regspace(1, Z.n_cols) # X = horizontal spacing Y = regspace(1, Z.n_rows) # Y = vertical spacing XI = regspace(X.min(), 1.0/2.0, X.max()) # magnify by approx 2 YI = regspace(Y.min(), 1.0/3.0, Y.max()) # magnify by approx 3 ZI = mat() interp2(X, Y, Z, XI, YI, ZI) # use linear interpolation by default ZI.save("output_image.pgm", pgm_binary)
x = linspace(0,4*datum.pi,100) y = cos(x) p = polyfit(x,y,10)
x1 = linspace(0,4*datum.pi,100) y1 = cos(x1) p1 = polyfit(x1,y1,10) y2 = polyval(p1,x1)
mean( M )
mean( M, dim ) mean( Q ) mean( Q, dim ) |
(form 1)
(form 2) (form 1) (form 2) |
⎫ ⎪ ⎬ mean (average value) ⎪ ⎭ |
median( M ) median( M, dim ) |
(form 1) (form 2) |
⎫ ⎪ ⎬ median ⎪ ⎭ |
stddev( M ) stddev( M, norm_type ) stddev( M, norm_type, dim ) |
(form 1a) (form 1b) (form 2) |
⎫ ⎪ ⎬ standard deviation ⎪ ⎭ |
var( M ) var( M, norm_type ) var( M, norm_type, dim ) |
(form 1a) (form 1b) (form 2) |
⎫ ⎪ ⎬ variance ⎪ ⎭ |
spread( M ) spread( M, dim ) |
(form 1) (form 2) |
⎫ ⎪ ⎬ spread (difference between max and min) ⎪ ⎭ |
A = mat(5, 5, fill.randu) B = mean(A) C = var(A) m = mean(mean(A)) v = mat(5, 1, fill.randu) x = var(v)
X = mat(4, 5, fill.randu) Y = mat(4, 5, fill.randu) C = cov(X,Y) D = cov(X,Y, 1)
X = mat(4, 5, fill.randu) Y = mat(4, 5, fill.randu) R = cor(X,Y) S = cor(X,Y, 1)
hist( X ) | (form 1a) | |
hist( X, n_bins ) | (form 1b) | |
hist( X, centers ) | (form 1c) | |
hist( X, centers, dim ) | (form 2) |
v = mat(1000, 1, fill.randn) # Gaussian distribution h1 = hist(v, 11) h2 = hist(v, linspace(-2,2,11))
histc( X, edges ) | (form 1) | |
histc( X, edges, dim ) | (form 2) |
v = mat(1000, 1, fill.randn) # Gaussian distribution h = histc(v, linspace(-2,2,11))
quantile( X, P ) | (form 1) | |
quantile( X, P, dim ) | (form 2) |
V = mat(1000, 1, fill.randn) # Gaussian distribution P = mat([ 0.25, 0.50, 0.75 ]) Q = quantile(V, P)
A = mat(5, 4, fill.randu) coeff = mat() score = mat() latent = mat() tsquared = mat() princomp(coeff, score, latent, tsquared, A)
1 ⎧ (x-m)2 ⎫
y = ‒‒‒‒‒‒‒ exp ⎪ −0.5 ‒‒‒‒‒‒ ⎪
s √(2π) ⎩ s2 ⎭
X = mat(10, 1, fill.randu) M = mat(10, 1, fill.randu) S = mat(10, 1, fill.randu) P1 = normpdf(X) P2 = normpdf(X, M, S ) P3 = normpdf(1.23, M, S ) P4 = normpdf(X, 4.56, 7.89) P5 = normpdf(1.23, 4.56, 7.89)
⎧ 1 ⎧ (x-m)2 ⎫ ⎫
y = log ⎪ ‒‒‒‒‒‒‒ exp ⎪ −0.5 ‒‒‒‒‒‒ ⎪ ⎪
⎩ s √(2π) ⎩ s2 ⎭ ⎭
⎧ (x-m)2 ⎫
= −log(s √(2π)) + ⎪ −0.5 ‒‒‒‒‒‒ ⎪
⎩ s2 ⎭
X = mat(10, 1, fill.randu) M = mat(10, 1, fill.randu) S = mat(10, 1, fill.randu) P1 = log_normpdf(X) P2 = log_normpdf(X, M, S ) P3 = log_normpdf(1.23, M, S ) P4 = log_normpdf(X, 4.56, 7.89) P5 = log_normpdf(1.23, 4.56, 7.89)
X = mat(10, 1, fill.randu) M = mat(10, 1, fill.randu) S = mat(10, 1, fill.randu) P1 = normcdf(X) P2 = normcdf(X, M, S ) P3 = normcdf(1.23, M, S ) P4 = normcdf(X, 4.56, 7.89) P5 = normcdf(1.23, 4.56, 7.89)
M = mat(5, 1, fill.randu) B = mat(5, 5, fill.randu) C = B.t() * B X = mvnrnd(M, C, 100)
from random import randint X = chi2rnd(2, 5, 6) A = mat(5, 6) A.imbue(lambda: randint(1,10)) # imbue with random integers B = chi2rnd(A)
X = mat(5, 5, fill.randu) S = X.t() * X W = wishrnd(S, 6.7)
X = mat(5, 5, fill.randu) T = X.t() * X W = iwishrnd(T, 6.7)
running_stat | (double-precision floating point) | |
frunning_stat | (single-precision floating point) | |
cx_running_stat | (complex double-precision floating point) | |
cx_frunning_stat | (complex single-precision floating point) |
X(scalar) | |
update the statistics using the given scalar |
X.min() | |
current minimum value |
X.max() | |
current maximum value |
X.spread() | |
current range |
X.mean() | |
current mean or average value |
X.var() and X.var(norm_type) | |
current variance |
X.stddev() and X.stddev(norm_type) | |
current standard deviation |
X.reset() | |
reset all statistics and set the number of samples to zero |
X.count() | |
current number of samples |
from random import normalvariate stats = running_stat() for i in range(10000): sample = normalvariate(0, 1) # normal distribution stats(sample) print("mean = " + str(stats.mean())) print("var = " + str(stats.var())) print("min = " + str(stats.min())) print("max = " + str(stats.max()))
running_stat_vec | (double-precision floating point) | |
frunning_stat_vec | (single-precision floating point) | |
cx_running_stat_vec | (complex double-precision floating point) | |
cx_frunning_stat_vec | (complex single-precision floating point) | |
running_stat_vec(calc_cov) | (double-precision floating point) | |
frunning_stat_vec(calc_cov) | (single-precision floating point) | |
cx_running_stat_vec(calc_cov) | (complex double-precision floating point) | |
cx_frunning_stat_vec(calc_cov) | (complex single-precision floating point) |
X(vector) | |
update the statistics using the given vector |
X.min() | |
vector of current minimum values |
X.max() | |
vector of current maximum values |
X.spread() | |
vector of current ranges |
X.mean() | |
vector of current means |
X.var() and X.var(norm_type) | |
vector of current variances |
X.stddev() and X.stddev(norm_type) | |
vector of current standard deviations |
X.cov() and X.cov(norm_type) | |
matrix of current covariances; valid if calc_cov=true during construction of running_stat_vec |
X.reset() | |
reset all statistics and set the number of samples to zero |
X.count() | |
current number of samples |
stats = running_stat_vec() for i in range(10000): sample = mat(5, 1, fill.randu) stats(sample) stats.mean().print("mean = ") stats.var().print("var = ") stats.max().print("max = ") more_stats = running_stat_vec(True) for i in range(20): sample = mat(1, 3, fill.randu) sample[1] -= sample[0] sample[2] += sample[1] more_stats(sample) more_stats.cov().print("covariance matrix = ") sd = more_stats.stddev() (more_stats.cov() / (sd.t() * sd)).print("correlations = ")
keep_existing | use the centroids specified in the means matrix as the starting point | |
static_subset | use a subset of the data vectors (repeatable) | |
random_subset | use a subset of the data vectors (random) | |
static_spread | use a maximally spread subset of data vectors (repeatable) | |
random_spread | use a maximally spread subset of data vectors (random start) |
static_spread
and random_spread
can be much more time consuming than with static_subset
and random_subset
d = 5 # dimensionality N = 10000 # number of vectors data = mat(d, N, fill.randu) means = mat() status = kmeans(means, data, 2, random_subset, 10, True) if not status: print("clustering failed") means.print("means:")
datum.pi
|
π, the ratio of any circle's circumference to its diameter | |
datum.inf
|
∞, infinity | |
datum.nan
|
“not a number” (NaN) caveat: NaN is not equal to anything, even itself | |
datum.e
|
base of the natural logarithm | |
datum.sqrt2
|
square root of 2 | |
datum.sqrt2pi
|
square root of 2π | |
datum.eps
|
machine epsilon: the difference between 1 and the value least greater than 1 that is representable (type and machine dependent) | |
datum.log_min
|
log of minimum non-zero value (type and machine dependent) | |
datum.log_max
|
log of maximum value (type and machine dependent) | |
datum.euler
|
Euler's constant, aka Euler-Mascheroni constant | |
datum.gratio
|
golden ratio | |
datum.m_u
|
atomic mass constant (in kg) | |
datum.N_A
|
Avogadro constant | |
datum.k
|
Boltzmann constant (in joules per kelvin) | |
datum.k_evk
|
Boltzmann constant (in eV/K) | |
datum.a_0
|
Bohr radius (in meters) | |
datum.mu_B
|
Bohr magneton | |
datum.Z_0
|
characteristic impedance of vacuum (in ohms) | |
datum.G_0
|
conductance quantum (in siemens) | |
datum.k_e
|
Coulomb's constant (in meters per farad) | |
datum.eps_0
|
electric constant (in farads per meter) | |
datum.m_e
|
electron mass (in kg) | |
datum.eV
|
electron volt (in joules) | |
datum.ec
|
elementary charge (in coulombs) | |
datum.F
|
Faraday constant (in coulombs) | |
datum.alpha
|
fine-structure constant | |
datum.alpha_inv
|
inverse fine-structure constant | |
datum.K_J
|
Josephson constant | |
datum.mu_0
|
magnetic constant (in henries per meter) | |
datum.phi_0
|
magnetic flux quantum (in webers) | |
datum.R
|
molar gas constant (in joules per mole kelvin) | |
datum.G
|
Newtonian constant of gravitation (in newton square meters per kilogram squared) | |
datum.h
|
Planck constant (in joule seconds) | |
datum.h_bar
|
Planck constant over 2 pi, aka reduced Planck constant (in joule seconds) | |
datum.m_p
|
proton mass (in kg) | |
datum.R_inf
|
Rydberg constant (in reciprocal meters) | |
datum.c_0
|
speed of light in vacuum (in meters per second) | |
datum.sigma
|
Stefan-Boltzmann constant | |
datum.R_k
|
von Klitzing constant (in ohms) | |
datum.b
|
Wien wavelength displacement law constant |
datum.nan
is not equal to anything, even itself;
to check whether a scalar x is finite,
use math.isfinite(x)
print("2.0 * pi = " + str(2.0 * datum.pi)) print("speed of light = " + str(datum.c_0)) print("log_max for doubles = " + str(datum.log_max))
A = mat(1000, 1000, fill.randu) B = mat(1000, 1000, fill.randu) timer = wall_clock() timer.tic() C = A * B n = timer.toc() print("elapsed: " + str(n))
libraries() # possible output: # # # PyArmadillo library status on install: # # MKL is not used. # OpenBLAS is used and is located at /usr/lib/x86_64-linux-gnu/libopenblas.so # ATLAS is not used. # BLAS is not used. # LAPACK is used and is located at /usr/lib/x86_64-linux-gnu/liblapack.so # FlexiBLAS is not used. # HDF5 is used and is located at /usr/lib/x86_64-linux-gnu/hdf5/serial/libhdf5.so # ARPACK is used and is located at /usr/lib/x86_64-linux-gnu/libarpack.so # SuperLU is used and is located at /usr/lib/x86_64-linux-gnu/libsuperlu.so # Accelerate is not used.
Matlab/Octave | PyArmadillo | Notes | ||
A(1, 1)
|
A[0, 0]
|
indexing in PyArmadillo starts at 0 | ||
A(k, k)
|
A[k-1, k-1]
|
|||
size(A,1)
|
A.n_rows
|
read only | ||
size(A,2)
|
A.n_cols
|
|||
size(Q,3)
|
A.n_slices
|
Q is a cube (3D array) | ||
numel(A)
|
A.n_elem
|
|||
A(:, k)
|
A[:, k]
|
this is a conceptual example only; exact conversion from Matlab/Octave to PyArmadillo syntax will require taking into account that indexing starts at 0 | ||
A(k, :)
|
A[k, :]
|
|||
A(:, p:q)
|
A[:, p:q]
|
|||
A(p:q, :)
|
A[p:q, :]
|
|||
A(p:q, r:s)
|
A[p:q, r:s]
|
|||
Q(p:q, r:s, t:u)
|
Q[p:q, r:s, t:u]
|
Q is a cube (3D array) | ||
Q(:, :, t:u)
|
Q[:, :, t:u]
|
|||
Q(:, :, k)
|
Q[single_slice, k]
|
|||
A'
|
A.t() or trans(A)
|
matrix transpose / Hermitian transpose
(for complex matrices, the conjugate of each element is taken) |
||
A = zeros(size(A))
|
A.zeros()
|
|||
A = ones(size(A))
|
A.ones()
|
|||
A = zeros(k)
|
A = zeros(k,k)
|
|||
A = ones(k)
|
A = ones(k,k)
|
|||
C = complex(A,B)
|
C = cx_mat(A,B)
|
|||
A * B
|
A * B
|
matrix multiplication | ||
A .* B
|
A @ B
|
element-wise multiplication | ||
A ./ B
|
A / B
|
element-wise division | ||
A \ B
|
solve(A,B)
|
conceptually similar to inv(A)*B, but more efficient | ||
A = A + 1;
|
A += 1
|
|||
A = A - 1;
|
A -= 1
|
|||
A = [ 1 2; 3 4; ]
|
A = mat([ [ 1, 2 ],
|
element initialisation | ||
X = A(:)
|
X = vectorise(A)
|
|||
X = [ A B ]
|
X = join_horiz(A,B)
|
|||
X = [ A; B ]
|
X = join_vert(A,B)
|
|||
A
|
A.print("A:")
|
|||
save ‑ascii 'A.txt' A
|
A.save("A.txt", raw_ascii)
|
Matlab/Octave matrices saved as ascii are readable by PyArmadillo (and vice-versa) | ||
load ‑ascii 'A.txt'
|
A.load("A.txt", raw_ascii)
|
|||
Form 1:
from pyarma import * A = mat(4, 5, fill.randu) B = mat(4, 5, fill.randu) C = A*B.t() C.print("C:") |
Form 2:
import pyarma as pa A = pa.mat(4, 5, pa.fill.randu) B = pa.mat(4, 5, pa.fill.randu) C = A*B.t() C.print("C:") |
solve_opts_*
flags renamed to solve_opts.*
(eg. solve_opts_fast
is now solve_opts.fast
)fill_*
flags renamed to fill.*
(eg. fill_zeros
is now fill.zeros
)