next up previous
Next: Linking with Fortran encoded Up: matrices Previous: matrices


Plain matrices in C++ and Fortran

Here is an example of a program that reads a matrix and a vector, multiplies the vector by the matrix and writes the answer. It includes a subroutine call for a subroutine that does the multiplication.

#include <iostream>
using namespace std;
#define MAX 50

void mulmatvec(int m, int n, double a[MAX][MAX], double x[MAX], double b[MAX]){
  int i,j;

  for(i = 0; i < m; i++){
    b[i] = 0.;
    for(j = 0; j < n; j++)
      b[i] += a[i][j]*x[j];
  }
  return;
}

int main(){
  int i,j,m,n;
  double a[MAX][MAX], x[MAX], b[MAX];

  cout << "Enter the number of rows in the matrix \n";
  cin >> m;
  cout << "Enter the number of columns in the matrix \n";
  cin >> n;

  cout << "Enter the matrix by rows\n";
  for(i = 0; i < m; i++)
    for(j = 0; j < n; j++)
      cin >> a[i][j];

  cout << "Enter the vector\n";
  for(j = 0; j < n; j++)
    cin >> x[j];

  mulmatvec(m,n,a,x,b);

  cout << "\nA*x = \n";
  for(i = 0; i < m; i++)
    cout << b[i] << "\n";
}

In this example we have used a doubly subscripted array of fixed dimension to hold the matrix. We need to distinguish two sets of numbers that specify the size of the matrix. First, there is the allocated size. The allocated number of rows and columns is set by the macro MAX. Then there is the working size. This is determined by the user at run time and kept in the variables m and n. They must both be less than or equal to MAX. The remaining allocated rows and columns are unused.

The matrix is passed to the subroutine in the same way that we pass singly subscripted arrays (vectors). In this example the function declaration specifies the complete allocated dimension of the matrix and vectors. Doubly subscripted matrices in C and C++ are stored by rows. So the 50 x 50 matrix is stored as follows:

   a[0][0] a[0][1] ... a[0][49] a[1][0] a[1][1] ... a[49][0] ... a[49][49]
with the second subscript varying most rapidly. The compiler needs to know the allocated number of columns in the matrix in order to be able to find the beginning of each row, starting from the first element a[0][0]. The allocated number of columns is the second number in the declaration double a[MAX][MAX];. The compiler actually ignores the first dimension in the declaration of each formal argument. So we can safely drop the first subscript dimension if we like and write it as
void matmul(int n, double a[][MAX], double x[], double b[]){
or equivalently as
void matmul(int n, double a[][MAX], double *x, double *b){
However, the compiler signals an error if we omit the second dimension in a[][MAX].

Here, the identifier a is technically a pointer to the first element of the array. And a[i] (and curiously, also a + i) is a pointer to the first element of the ith row.



Subsections
next up previous
Next: Linking with Fortran encoded Up: matrices Previous: matrices
Carleton DeTar 2012-10-22