How to Code Matrix Subtraction in C++

Matrix subtraction is a fairly straightforward operation to write computer code for because it's performed on an element-by-element basis. Since there's no built-in data type for matrices in C++, you must either find and use a class written by someone else or implement them yourself using multidimensional arrays. Code matrix subtraction by using nested "for" loops to subtract the elements in each matrix one by one.

Instructions

    • 1

      Declare matrices as multidimensional arrays. For example:

      int a[2][4] = {{1,2,3,4},{5,6,7,8}};

      int b[2][4] = {{0,1,2,3},{4,5,6,7}};

    • 2

      Create a new array to hold the difference of two others:

      int c[2][4];

    • 3

      Conduct the subtraction using two nested "for" loops as follows:

      for(int i=0;i<sizeof(a)/sizeof(a[0]);i++){

      for(int j=0;j<sizeof(a[0])/sizeof(a[0][0]);j++){

      c[i][j] = a[i][j] - b[i][j];

      }

      }

      The "sizeof" functions are used to determine the type-independent size of each dimension of one of the matrices so that the iterator variables operate correctly. This way the "for" loops are reusable for matrices of any size. Of course, the two matrices must be the same size as each other to subtract them, and this code assumes they are. You may wish to check the sizes programmatically if you're developing the code for use by others.

Related Searches:

Comments

Related Ads

Featured