/******************************************************************/ /* */ /* Matrix Manipulation */ /* */ /* Frank Schorfheide */ /* */ /******************************************************************/ /* filename: matrix.g ** created: 09/15/97 */ /* Clear the output screen */ cls; /* GAUSS is a matrix oriented programming environment to solve ** statistics and econometrics problems. Data are stored in ** m*n matrices */ /* Define a 3*3 matrix A, note that all command lines end with ";" ** also note the use of ~ and | */ A = ( 8 ~ 3 ~ 2 ) | /* row 1 */ ( 3 ~ 4 ~ 3 ) | /* row 2 */ ( 2 ~ 7 ~ 1 ) ; /* row 3 */ /* Print matrix A on the screen */ "Matrix A is equal to"; A; /* We can address columns, rows, submatrices as follows */ "The first row of matrix A is"; A[1,.]; "The second column of matrix A is"; A[.,2]; "The first two elements in the third row are"; A[3,1:2]; "Redefine the first two elements in the third row to be 0 0"; A[3,1:2] = zeros(1,2); "The matrix A is now"; A; " "; "Press any key to continue"; k = keyw; cls; /* We can also define a matrix of zeros or ones or the identity matrix */ B = ones(3,3); C = zeros(3,3); D = eye(3); "Matrix B, C, D are equal to"; B; C; D; /* We can create additive and multiplicative sequences with ** seqa(x,y,z) or seqm(x,y,z) where x is the starting value, ** y is the constant added or multiplied, and z is the number ** of elements in the sequence */ S1 = seqa(1,2,4); M1 = seqm(2,2,4); /* Now note the transpose operator */ "Additive Sequence"; S1'; "Multiplicative Sequence"; M1'; " "; "Press any key to continue"; k = keyw; cls; /* Matrix Operations */ /* redefine matrix B */ B = { 3 5 6, 3 8 9, 1 7 4 }; "A equals"; A; "B equals"; B; /* Sum of two matrices */ C = A + B; "C = A + B"; C; /* Product of two matrices */ C = A * B ; "C = A * B"; C; /* Element by element multiplication */ C = A .* B; "C = A .* B"; C; "Press any key to continue"; k = keyw; cls; "Matrix A equals"; A; "Take the square root"; sqrt(A); "Compare A^2..."; A^2; "and A*A..." A*A; " "; "Press any key to continue"; k = keyw; cls; "The inverse of A is"; inv(A); /* We can calculate eigenvalues and eigenvectors */ {la, ve} = eigv(A); "The eigenvalues of A are"; la'; "The eigenvector corresponding to the first eigenvalue is"; ve[.,1]; "Press any key to continue"; k = keyw; cls; "E X E R C I S E"; /* Exercise: Define matrices F = 3 5 6 G = 6 8 1 ** 2 5 2 1 3 8 ** 1 9 7 2 9 1 */ /* Let H be F plus G, print H */ /* Let L be inv(F)* ( G + H) and print the last two elements of the second column */