Matrices and Vectors
Content |
In this examples a macro named COLMAJOR is used to specify whether matrices are stored column major (if COLMAJOR equals 1) or row major (if COLMAJOR equals ).
In the program we use the CPP directives
#ifndef COLMAJOR #define COLMAJOR 1 #endif
for this purpose:
-
If you compile with -DCOLMAJOR=1 or -DCOLMAJOR=0 you can explicitly specify the storage order.
-
By default (i.e. you don't use the -D flag) the macro is defined such that is expands to 1.
Notes
-
Use the unsigned integer type size_t and the signed integer type ptrdiff_t (both defined in stddef.h) for dimensions and increments.
-
For dynamic memory allocation we use malloc (declared in stdlib.h). Memory allocated through malloc can be release by free. Hereby, memory must be released exactly once.
-
For printing values of type double use the %lf placeholder. Using the form %9.2lf reserves a total of 9 characters for the output with a decimal point and a precision of 2 digital places.
Exercise: Simple initialization and print functions for matrices
Complete the skeleton below:
-
Functions initGeMatix and printGeMatrix
-
First define the proper signature of the functions. Derive the signature from the use-case in main.
-
Once a signature is well defined you can start to implement the function.
-
-
Fix some of the function calls in main:
-
The increments incRowA and incColA need to be initialized depending on the storage order.
-
Allocate the right amount of memory for a \(m \times n\) matrix with elements of type double.
-
Print different matrix views as indicated by the preceding printf statement.
-
#include <stdlib.h> #include <stdio.h> #include <stddef.h> // function initGeMatrix /* Your Code here. */ // function printGeMatrix /* Your Code here. */ #ifndef COLMAJOR #define COLMAJOR 1 #endif int main() { printf("COLMAJOR = %d\n", COLMAJOR); size_t m = 5, n = 10; ptrdiff_t incRowA = COLMAJOR ? 0 : 0; // <- FIXME ptrdiff_t incColA = COLMAJOR ? 0 : 0; // <- FIXME // allocate memory for A double *A = malloc(m*n*sizeof(double)); if (!A) { abort(); } // initialize matrix A initGeMatrix(m, n, A, incRowA, incColA); // print matrix A printf("A =\n"); printGeMatrix(m, n, A, incRowA, incColA); // print how elements are stored in memory printf("memory layout of A:\n"); // use printGeMatrix! // <- Your code here // print a matrix view of A printf("A(0:2, 0:3) =\n"); printGeMatrix(0, 0, A, incRowA, incColA); // <- FIXME // print a matrix view of A printf("A(2:4, 3:8) =\n"); printGeMatrix(0, 0, A, incRowA, incColA); // <- FIXME // print a matrix view of A printf("A(2:4, 3:8)^T =\n"); printGeMatrix(0, 0, A, incRowA, incColA); // <- FIXME // release memory free(A); }