|
-
April 27th, 2016, 01:25 AM
#1
Sparse Matrix Operations
Hello !
I want to implement some operations with sparse matrix: addition, substraction, multiplication, multiplication with vector.
I have two matrix in Matrix Market format, namely two *.mtx files( "A.mtx", "B.mtx").
Till now, I am able to read matrix, to print and to write in text files.
I use this library: http://math.nist.gov/MatrixMarket/mmio/c/mmio.c
My code:
Code:
/*
* Read sparse matrix in MatrixMarket(*.mtx) format
* Stored method: coordinate format
*/
#define extfis ".txt"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
extern "C"
{
#include "mmio.h"
#include "mmio.c"
}
class SparseMatrix {
int ret_code;
MM_typecode matcode;
FILE *f;
int M, N, nz;
int i, *I, *J;
double *val;
const char* mtx_file;
string matrice;
string numefin;
public:
void Read (const char*);
void Show(string);
};
void SparseMatrix::Read(const char* mtx) {
mtx_file = mtx;
if ((f = fopen(mtx_file, "r")) == NULL)
exit(1);
if (mm_read_banner(f, &matcode) != 0)
{
printf("Could not process Matrix Market banner.\n");
exit(1);
}
if (mm_is_complex(matcode) && mm_is_matrix(matcode) &&
mm_is_sparse(matcode) )
{
printf("Sorry, this application does not support ");
printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode));
exit(1);
}
/* dimension*/
if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nz)) !=0)
exit(1);
/* storage */
I = (int *) malloc(nz * sizeof(int));
J = (int *) malloc(nz * sizeof(int));
val = (double *) malloc(nz * sizeof(double));
for (i=0; i<nz; i++)
{
fscanf(f, "%d %d %lg\n", &I[i], &J[i], &val[i]);
I[i]--;
J[i]--;
}
if (f !=stdin)
{
fclose(f);
}
}
void SparseMatrix::Show(string txt) {
/* print matrix */
/* write matrix in text file */
matrice = txt;
const char * c = matrice.c_str();
mm_write_banner(stdout, matcode);
mm_write_mtx_crd_size(stdout, M, N, nz);
ofstream output;
output.open(c);
cout << "Matrix " << matrice << ":" << endl;
for (i=0; i<nz; i++) {
fprintf(stdout, "%d %d %20.19g\n", I[i]+1, J[i]+1, val[i]);
output << I[i]+1 << " " << J[i]+1 << " " << val[i] << endl;
}
output.close();
//extract matrix name,without extension(.txt)
string nume_matrice = matrice.substr (0,1);
cout << "Matrix " << matrice << " is save in file" << nume_matrice << ".txt" << endl;
}
int main()
{
SparseMatrix matrixA;
SparseMatrix matrixB;
matrixA.Read("A.mtx");
matrixA.Show("A.txt");
matrixB.Read("B.mtx");
matrixB.Show("B.txt");
return 0;
}
So, please help me with addition(A+B) implementation.
All the best !
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|