In: Computer Science
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;
int ReadNumbers( const string & s, vector <double>
& v );
void import_matrix_from_txt_file(const char* filename_X, vector
<double>& v, int& rows, int& cols);
int main(){
vector <double> v;
int rows=0;
int cols=0;
import_matrix_from_txt_file("x.txt",v,rows,cols);
}
int ReadNumbers( const string & s, vector <double>
& v ) {
istringstream is( s );
double n;
while( is >> n ) {
v.push_back( n );
}
return v.size();
}
void import_matrix_from_txt_file(const char* filename_X, vector
<double>& v, int& rows, int& cols){
ifstream file_X;
string line;
file_X.open(filename_X);
if (file_X.is_open())
{
int i=0;
getline(file_X, line);
cols =ReadNumbers( line, v );
cout << "cols:" << cols << endl;
for ( i=1;i<32767;i++){
if ( getline(file_X, line) == 0 ) break;
ReadNumbers( line, v );
}
rows=i;
cout << "rows :" << rows << endl;
if(rows >32766) cout<< "N must be smaller than
MAX_INT";
file_X.close();
}
else{
cout << "file open failed";
}
cout << "v:" << endl;
for (int i=0;i<rows;i++){
for (int j=0;j<cols;j++){
cout << v[i*cols+j] << "\t" ;
}
cout << endl;
}
}
// Finding Determinant
int determinantOfMatrix(int mat[N][N], int n)
{
int D = 0; // Initialize result
// Base case : if matrix contains single element
if (n == 1)
return mat[0][0];
int temp[N][N]; // To store cofactors
int sign = 1; // To store sign multiplier
// Iterate for each element of first row
for (int f = 0; f < n; f++)
{
// Getting Cofactor of mat[0][f]
getCofactor(mat, temp, 0, f, n);
D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1);
// terms are to be added with alternate sign
sign = -sign;
}
return D;
}