Sunday, November 20, 2011

Creating, Destroying and Copying A Matrix using NMat

Before reading about how create, destroy and copy a matrix using the NMat library, make sure you've read this article:
The article explains the principles and the structure of the matrices used by NMat.

The operations Create, Destroy and Copy are implemented by the following functions:
/*
 * Description:
 *  Alocates spaces for a NMatrix structure according to the parameters
 * @rows si @columns.
 * Parameters:
 *  rows - the number of rows
 *  columns - the number of columns
 * Returns:
 *  A pointer to the allocated matrix structure.
 */
NMatrix* NMatrix_Create(integer rows, integer columns);
/*
 * Description:
 *  Free the space hold by a NMatrix structure
 * Parameters:
 *  matrix - a pointer to the NMatrix structure
 * Returns:
 *  NULL
 * Preconditions:
 *  @matrix must not be NULL
 */
NMatrix* NMatrix_Destroy(NMatrix *matrix);
/*
 * Description:
 *  Creates a hard copy of the matrix @source
 * Parameters:
 *  source - the matrix who shall be copied
 *  destination - the matrix where the copy
 *       will be stored
 * Returns:
 *  A pointer to the clone matrix
 * Preconditions:
 *  @matrix must not be NULL
 */
NMatrix* NMatrix_Clone(const NMatrix *source);
If you want to see how the functions are implemented, click the link below:
Example:
#include<stdio.h>
#include"NMatrix.h"

void PrintMatrix(NMatrix *mat)
{
   integer i = 0, j = 0;
   for (i = 0; i < mat->rows; i++)
   {
      for (j = 0; j < mat->columns; j++)
      {
         printf("%+f ", mat->data[i][j]);
      }
      putchar('\n');
   }
   putchar('\n');
}

int main(int argc, char *argv[])
{
   NMatrix* mat = NULL;
   NMatrix* matCopy = NULL;
   /*Creating a 2x2 NMatrix structure*/
   mat = NMatrix_Create(2, 2);
   /*Assigning values to the structure*/
   mat->data[0][0] = 3.3;
   mat->data[0][1] = 2.1;
   mat->data[1][0] = 5.2;
   mat->data[1][1] = -6.3;
   /*Printing the matrix*/
   puts("The original matrix: ");
   PrintMatrix(mat);
   /*Creating a copy of the first matrix*/
   matCopy = NMatrix_Clone(mat);
   /*Destroying the first matrix*/
   mat = NMatrix_Destroy(mat);
   /*Printing the second matrix*/
   puts("The copy of the matrix: ");
   PrintMatrix(matCopy);
   return 0;
}
/*Output:
 The original matrix:
 +3.300000 +2.100000
 +5.200000 -6.300000

 The copy of the matrix:
 +3.300000 +2.100000
 +5.200000 -6.300000
 */

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger