Matrix extra

Matrix extra — more matrix operations

Functions

Types and Values

Includes

#include <gretl/libgretl.h>
#include <gretl/matrix_extra.h>

Description

Functions that convert between gretl_matrix and other datatypes; also printing of gretl_matrices and some functions relating to masking and cutting rows and/or columns of matrices.

Functions

gretl_vector_from_array ()

gretl_vector *
gretl_vector_from_array (const double *x,
                         int n,
                         GretlMatrixMod mod);

Parameters

x

pointer to array of elements.

 

n

number of elements.

 

mod

modifier flag: either GRETL_MOD_NONE, or GRETL_MOD_SQUARE to use the squares of the elements of x .

 

Returns

pointer to a newly allocated gretl_vector containing the elements of x (or their squares), or NULL on failure. Missing values in x are skipped.


gretl_vector_from_series ()

gretl_vector *
gretl_vector_from_series (const double *x,
                          int t1,
                          int t2);

Parameters

x

series from data array.

 

t1

starting observation.

 

t2

ending observation.

 

Returns

a newly allocated gretl_vector containing the values of the given data series for the given range, or NULL on failure. Any missing values in the input array are preserved as NaNs in the output.


gretl_matrix_from_2d_array ()

gretl_matrix *
gretl_matrix_from_2d_array (const double **X,
                            int rows,
                            int cols);

Parameters

X

two-dimensional array of doubles.

 

rows

number of rows in target matrix.

 

cols

number of columns in target matrix.

 

Returns

allocated gretl_matrix, the elements of which are set to the values in X , or NULL on allocation failure.


gretl_matrix_from_scalar ()

gretl_matrix *
gretl_matrix_from_scalar (double x);

Parameters

x

scalar to be "promoted".

 

Returns

allocated 1 x 1 gretl_matrix, the single element of which is set to x , or NULL on allocation failure.


gretl_vcv_matrix_from_model ()

gretl_matrix *
gretl_vcv_matrix_from_model (MODEL *pmod,
                             const char *select,
                             int *err);

Produces all or part of the covariance matrix for pmod in the form of a gretl_matrix. Storage is allocated, to be freed by the caller. If select is not NULL, it should be an array with non-zero elements in positions corresponding to the desired rows (and columns), and zero elements otherwise.

Parameters

pmod

pointer to model

 

select

char array indicating which rows and colums to select (or NULL for the full matrix).

 

err

location to receive error code.

 

Returns

the covariance matrix, or NULL on error.


gretl_coeff_vector_from_model ()

gretl_vector *
gretl_coeff_vector_from_model (const MODEL *pmod,
                               const char *select,
                               int *err);

Produces all or part of the coefficient vector for pmod in the form of a gretl column vector. Storage is allocated, to be freed by the caller. If select is non-NULL, it should be an array with non-zero elements in positions corresponding to the desired rows and zero elements otherwise.

Parameters

pmod

pointer to model

 

select

char array indicating which rows to select (or NULL for the full vector).

 

err

location to receive error code.

 

Returns

the coefficient vector, or NULL on error.


gretl_covariance_matrix_from_varlist ()

gretl_matrix *
gretl_covariance_matrix_from_varlist (const int *list,
                                      const DATASET *dset,
                                      gretl_matrix **means,
                                      int *errp);

Parameters

list

list of variables by ID number.

 

dset

dataset struct.

 

means

pointer to pick up vector of means, or NULL to discard.

 

errp

pointer to receive non-zero error code in case of failure, or NULL.

 

Returns

the variance-covariance matrix of the listed variables (over the currently defined data sample), or NULL in case of failure.


gretl_matrix_row_to_array ()

int
gretl_matrix_row_to_array (const gretl_matrix *m,
                           int i,
                           double *x);

Copies the values from row i of matrix m into the array x , which should already be allocated to the correct size.

Parameters

m

source matrix.

 

i

the row from which values should be copied.

 

x

array of doubles large enough to hold a row from m .

 

Returns

0 on sucess, non-zero if the row is out of bounds.


gretl_matrix_get_columns ()

double **
gretl_matrix_get_columns (const gretl_matrix *m,
                          int *err);

Constructs a two-dimensional array in which each sub-array is a pointer to a column of m . The content of these arrays belongs to m and must not be freed; only the returned pointer itself should be freed.

Parameters

m

source matrix.

 

err

location to receive error code.

 

Returns

the constructed array on success or NULL on failure.


gretl_matrix_data_subset_masked ()

gretl_matrix *
gretl_matrix_data_subset_masked (const int *list,
                                 const DATASET *dset,
                                 int t1,
                                 int t2,
                                 const char *mask,
                                 int *err);

Creates a gretl matrix holding the subset of variables from dset specified by list , over the sample range t1 to t2 , inclusive. Variables are in columns. mask should be an array of char of length (t2 - t1 + 1) with 1s in the positions of observations to exclude from the subset and zeros elsewhere. This apparatus can be used to exclude missing observations.

Parameters

list

list of variable to process.

 

dset

dataset struct.

 

t1

starting observation.

 

t2

ending observation.

 

mask

missing observations mask, or NULL.

 

err

location to receive error code.

 

Returns

allocated matrix or NULL on failure.


gretl_matrix_data_subset ()

gretl_matrix *
gretl_matrix_data_subset (const int *list,
                          const DATASET *dset,
                          int t1,
                          int t2,
                          int missop,
                          int *err);

Creates a matrix holding the subset of variables from dset specified by list , over the sample range t1 to t2 , inclusive. Series are in columns. The missop flag can be M_MISSING_OK to indicate that it's OK to include missing values in the matrix, M_MISSING_ERROR (it's an error if any missing values are found), or M_MISSING_SKIP (observations with any missing values are omitted from the matrix).

Parameters

list

list of series to process, or NULL to include all series except "const".

 

dset

pointer to dataset struct.

 

t1

starting observation.

 

t2

ending observation.

 

missop

how to handle missing observations.

 

err

location to receive error code.

 

Returns

allocated matrix or NULL on failure.


gretl_matrix_data_subset_special ()

gretl_matrix *
gretl_matrix_data_subset_special (const int *list,
                                  const DATASET *dset,
                                  const gretl_matrix *mmask,
                                  int *err);

Creates a gretl matrix holding the subset of variables from dset specified by list , using the observations (data rows) selected by non-zero elements in mmask . This is designed to support the gretl "libset" variable matrix_mask.

The length of the vector mmask must equal the number of observations in the dataset, the member n of dset .

Parameters

list

list of variables to process.

 

dset

dataset struct.

 

mmask

matrix holding desired observations mask.

 

err

location to receive error code.

 

Returns

allocated matrix or NULL on failure.


gretl_dataset_from_matrix ()

DATASET *
gretl_dataset_from_matrix (const gretl_matrix *m,
                           const int *list,
                           gretlopt opt,
                           int *err);

Creates a gretl dataset from matrix m , either using the columns specified in list or using all columns if list is NULL.

Parameters

m

source matrix.

 

list

list of columns (1-based) to include, or NULL.

 

opt

may include OPT_B to attempt "borrowing" of data; OPT_N to use plain numbers as variable names; OPT_R to use row-names as observation markers, if present; OPT_S when called from the "store" command.

 

err

location to receive error code.

 

Returns

pointer to new dataset information struct on success, or NULL on failure.


gretl_dataset_from_matrices ()

DATASET *
gretl_dataset_from_matrices (const gretl_matrix *m1,
                             const gretl_matrix *m2,
                             int *err);

Creates a gretl dataset from the side-by-side concatenation of m1 and m2 . Storage for the values is "borrowed" from the columns of the matrices. Column names are used to label the series, if present; otherwise the labels are "v1", "v2" and so on.

The two matrices must have the same number of rows. Rownames on either matrix are disregarded.

Parameters

m1

first source matrix.

 

m2

second source matrix.

 

err

location to receive error code.

 

Returns

pointer to new dataset on success, or NULL on failure.


write_matrix_as_dataset ()

int
write_matrix_as_dataset (const char *fname,
                         gretlopt opt,
                         PRN *prn);

gretl_plotfit_matrices ()

int
gretl_plotfit_matrices (const double *yvar,
                        const double *xvar,
                        FitType fit,
                        int t1,
                        int t2,
                        gretl_matrix **py,
                        gretl_matrix **pX);

Creates a vector y and matrix X based on the input yvar , xvar and fit , using the given sample range. An observation is skipped if either yvar or xvar is missing at that observation.

Parameters

yvar

the y variable.

 

xvar

the x variable.

 

fit

type of fit sought.

 

t1

starting observation.

 

t2

ending observation.

 

py

location to receive y vector.

 

pX

location to receive X matrix.

 

Returns

0 on success, non-zero code on error.


gretl_matrix_read_from_file ()

gretl_matrix *
gretl_matrix_read_from_file (const char *fname,
                             int import,
                             int *err);

Reads a matrix from a file by the name fname ; if it's a text file the column separator must be space or tab. It is assumed that the dimensions of the matrix (number of rows and columns) are found on the first line of the file, so no heuristics are necessary. In case of error err is filled appropriately.

Parameters

fname

name of file.

 

import

non-zero means we're importing via dotdir.

 

err

location to receive error code.

 

Returns

The matrix as read from file, or NULL.


gretl_matrix_write_to_file ()

int
gretl_matrix_write_to_file (gretl_matrix *A,
                            const char *fname,
                            int export);

Writes the matrix A to a file by the name fname ; if it's a text file, the column separator is tab. The number of rows and columns are written on the first line of the file.

Parameters

A

matrix to write.

 

fname

name of file.

 

export

non-zero means we're exporting via dotdir.

 

Returns

0 on successful completion, non-zero code on error.


gretl_matrix_print_to_prn ()

void
gretl_matrix_print_to_prn (const gretl_matrix *m,
                           const char *msg,
                           PRN *prn);

Prints the matrix m to prn .

Parameters

m

matrix to print.

 

msg

accompanying message text (or NULL if no message is wanted).

 

prn

pointer to gretl printing struct.

 

gretl_matrix_print_range ()

void
gretl_matrix_print_range (const gretl_matrix *m,
                          const char *msg,
                          int rmin,
                          int rmax,
                          PRN *prn);

Prints the specified rows of matrix m to prn .

Parameters

m

matrix to print.

 

rmin

first row to print.

 

prn

last row to print.

 

gretl_matrix_print_with_col_heads ()

void
gretl_matrix_print_with_col_heads (const gretl_matrix *m,
                                   const char *title,
                                   const char **heads,
                                   const DATASET *dset,
                                   PRN *prn);

Prints the matrix m to prn , with column headings given by heads .

Parameters

m

T x k matrix to print.

 

title

accompanying title (or NULL if no title is wanted).

 

heads

array of k strings to identify the columns.

 

prn

pointer to gretl printing struct.

 

gretl_matrix_print_with_format ()

void
gretl_matrix_print_with_format (const gretl_matrix *m,
                                const char *fmt,
                                int wid,
                                int prec,
                                PRN *prn);

Prints the matrix m to prn , with the elements of m formatted as specified by fmt , wid and prec . The arguments wid and/or prec are required only if fmt contains one or more placeholders ("*") to be filled out. For example, if fmt is "%14.6f" then neither wid nor prec is needed and both should be set to 0; if fmt is "%*.6f" then a wid value is needed but prec should be 0.

Parameters

m

matrix to print.

 

fmt

a printf-type format string.

 

wid

an integer width, or 0.

 

prec

an integer precision, or 0.

 

prn

pointer to gretl printing struct.

 

debug_print_matrix ()

void
debug_print_matrix (const gretl_matrix *m,
                    const char *msg);

Prints the matrix m to stderr with high precision, along with the address of the matrix struct.

Parameters

m

matrix to print.

 

msg

accompanying message text (or NULL if no message is wanted).

 

gretl_matrix_cut_cols ()

int
gretl_matrix_cut_cols (gretl_matrix *m,
                       const char *mask);

In-place reduction of m based on mask : the masked cols are cut out of m .

Parameters

m

matrix to process.

 

mask

character array of length equal to the cols of m , with 1s indicating cols to be cut, 0s for cols to be retained.

 

Returns

0 on success, non-zero on error.


gretl_matrix_cut_rows ()

int
gretl_matrix_cut_rows (gretl_matrix *m,
                       const char *mask);

In-place reduction of m based on mask : the masked rows are cut out of m .

Parameters

m

matrix to process.

 

mask

character array of length equal to the rows of m , with 1s indicating rows to be cut, 0s for rows to be retained.

 

Returns

0 on success, non-zero on error.


gretl_matrix_cut_rows_cols ()

int
gretl_matrix_cut_rows_cols (gretl_matrix *m,
                            const char *mask);

In-place reduction of m based on mask : the masked rows and columns are cut out of m . (The data array within m is not "physically" resized.)

Parameters

m

square matrix to process.

 

mask

character array of length equal to the dimension of m , with 1s indicating rows and columns to be cut, 0s for rows/columns to be retained.

 

Returns

0 on success, non-zero on error.


gretl_matrix_zero_row_mask ()

char *
gretl_matrix_zero_row_mask (const gretl_matrix *m,
                            int *err);

Checks matrix m for rows that are all zero. If there are any such rows, constructs a mask of length equal to the number of rows in m , with 1s indicating zero rows, 0s elsewhere. If there are no such rows, returns NULL.

E_ALLOC is written to err in case a mask should have been constructed but allocation failed.

Parameters

m

matrix to process.

 

err

location to receive error code.

 

Returns

allocated mask or NULL.


gretl_matrix_zero_col_mask ()

char *
gretl_matrix_zero_col_mask (const gretl_matrix *m,
                            int *err);

Checks matrix m for columns that are all zero. If there are any such columns, constructs a mask of length equal to the number of columns in m , with 1s indicating zero columns, 0s elsewhere. If there are no such columns, returns NULL.

E_ALLOC is written to err in case a mask should have been constructed but allocation failed.

Parameters

m

matrix to process.

 

err

location to receive error code.

 

Returns

allocated mask or NULL.


gretl_matrix_zero_diag_mask ()

char *
gretl_matrix_zero_diag_mask (const gretl_matrix *m,
                             int *err);

Checks square matrix m for diagonal elements that are zero. If there are any such, constructs a mask of length equal to the number of rows (and columns) of m , with 1s indicating the zero diagonal entries. If there are no zero diagonal elements, returns NULL.

E_ALLOC is written to err in case a mask should have been constructed but allocation failed.

Parameters

m

matrix to process.

 

err

location to receive error code.

 

Returns

allocated mask or NULL.


gretl_matrix_rank_mask ()

char *
gretl_matrix_rank_mask (const gretl_matrix *m,
                        int *err);

Performs a QR decomposition of matrix m and uses this to assess the rank of m . If m is not of full rank, constructs a mask of length equal to the numbers of columns in m , with 1s in positions corresponding to diagonal elements of R that are effectively 0, and 0s elsewhere. If m is of full column rank, NULL is returned.

E_ALLOC is written to err in case a mask should have been constructed but allocation failed.

Parameters

m

matrix to process.

 

err

location to receive error code.

 

Returns

allocated mask or NULL.


gretl_matrix_mp_ols ()

int
gretl_matrix_mp_ols (const gretl_vector *y,
                     const gretl_matrix *X,
                     gretl_vector *b,
                     gretl_matrix *vcv,
                     gretl_vector *uhat,
                     double *s2);

Computes OLS estimates using Cholesky factorization, via the GMP multiple-precision library, and puts the coefficient estimates in b . Optionally, calculates the covariance matrix in vcv and the residuals in uhat .

Parameters

y

dependent variable vector.

 

X

matrix of independent variables.

 

b

vector to hold coefficient estimates.

 

vcv

matrix to hold the covariance matrix of the coefficients, or NULL if this is not needed.

 

uhat

vector to hold the regression residuals, or NULL if these are not needed.

 

s2

pointer to receive residual variance, or NULL. Note: if s2 is NULL, the "vcv" estimate will be plain (X'X)^{-1}.

 

Returns

0 on success, non-zero error code on failure.


gretl_quadrule_matrix_new ()

gretl_matrix *
gretl_quadrule_matrix_new (int n,
                           int method,
                           double a,
                           double b,
                           int *err);

Calculates a quadrature "rule" (i.e. a set of abscissae or nodes and associated weights) for use in numerical integration. The three supported methods are Gauss-Hermite, Gauss-Legendre and Gauss-Laguerre.

If the optional parameters are not to be used, both should be given the value NADBL.

If the method is QUAD_GHERMITE, the default weights are W(x) = exp(-x^2), but a and b can be used to apply a normal scaling with mean a and standard deviation b . The limits of integration are in principle minus infinity and plus infinity.

If the method is QUAD_LEGENDRE the weights are W(x) = 1 and the default limits of integration are -1 and 1, but a and b can be used to adjust the lower and upper limit respectively.

In the QUAD_LAGUERRE case W(x) = exp(-x) and the limits of integration are 0 and plus infinity; a and b are ignored.

Parameters

n

the order (i.e. the number of abscissae and weights).

 

method

should be one of the values in QuadMethod.

 

a

optional parameter (see below).

 

b

optional parameter (see below).

 

err

location to receive error code.

 

Returns

an n x 2 matrix containing the abscissae in the first column and the weights in the second, or NULL on failure.


gretl_gauss_hermite_matrix_new ()

gretl_matrix *
gretl_gauss_hermite_matrix_new (int n,
                                int *err);

gretl_matrix_2d_convolution ()

gretl_matrix *
gretl_matrix_2d_convolution (const gretl_matrix *A,
                             const gretl_matrix *B,
                             int *err);

Computes the 2-dimensional convolution of the matrices A and B . The code borrows from Octave's conv2.m.

Parameters

A

first matrix.

 

B

second matrix.

 

err

location to receive error code.

 

Returns

newly allocated convolution matrix, or NULL on failure.


vector_from_strings ()

gretl_matrix *
vector_from_strings (char **S,
                     int ns,
                     const char *fmt,
                     int *nvals,
                     int *err);

Types and Values

enum MMissingCode

Members

M_MISSING_OK

   

M_MISSING_ERROR

   

M_MISSING_SKIP

   

M_MISSING_TRIM

   

enum QuadMethod

Members

QUAD_GHERMITE

   

QUAD_LEGENDRE

   

QUAD_LAGUERRE

   

QUAD_INVALID