Skip to content

Instantly share code, notes, and snippets.

@philopaterwaheed
Created March 6, 2024 08:06
Show Gist options
  • Save philopaterwaheed/94fddab71d36e20a2dba2c4b0cf36f16 to your computer and use it in GitHub Desktop.
Save philopaterwaheed/94fddab71d36e20a2dba2c4b0cf36f16 to your computer and use it in GitHub Desktop.
multiply matrix from and out to files using vectors
#include <cctype>
#include <istream>
#include <algorithm>
#include <bits/chrono.h>
#include <ctime>
#include <iostream>
#include <chrono>
#include <fstream>
#include <string>
#include <vector>
std :: vector<std::vector<int>> matrix_mult (std :: vector<std::vector<int>> a,std :: vector<std::vector<int>> b ) ;
int main (){
std :: ifstream matrix_file = std::ifstream ("matrix.txt") ;
std :: ifstream vector_file = std::ifstream ("vector.txt") ;
std:: vector<std::vector<int>> matrix ;
std:: vector<std::vector<int>> vector ;
if (matrix_file.is_open()){
int index = 0 ;
while (matrix_file){
std :: string line , input = "";
std::getline(matrix_file,line);
if (line.size() != 0 ){
matrix.push_back({});
for (auto c : line){
if (c == ',')
{
matrix[index].push_back(std::stoi((input)));
input.clear();
}
else if (std::isdigit(c)){
input.push_back(c);
}
}
matrix[index].push_back(std::stoi((input)));
index++;
}
}
}
if (vector_file.is_open()){
int index = 0 ;
while (vector_file){
std :: string line , input = "";
std::getline(vector_file,line);
if (line.size() != 0 ){
vector.push_back({});
for (auto c : line){
if (c == ',')
{
vector[index].push_back(std::stoi((input)));
input.clear();
}
else if (std::isdigit(c)){
input.push_back(c);
}
}
vector[index].push_back(std::stoi((input)));
index++;
}
}
}
auto out = matrix_mult (matrix , vector);
// for(auto x : matrix ){
// for (auto y : x ){
// std :: cout << "x" <<y;
// }
// std :: cout << '\n';
// }
std :: ofstream output_file = std::ofstream ("output.txt");
if (output_file.is_open())
{
for(auto x : out ){
output_file << "[";
for (auto y : x ){
output_file <<y<< "," ;
}
output_file<< "]\n";
}
}
}
std::vector<std::vector<int>> matrix_mult(std::vector<std::vector<int>> m1, std::vector<std::vector<int>> m2) {
std::vector<std::vector<int>> out(m1.size(), std::vector<int>(m2[0].size() , 0));
for (std::size_t row = 0; row < out.size(); row++) {
for (std::size_t col = 0; col < out[0].size(); col++) {
for (std::size_t inner = 0; inner < m2.size(); inner++) {
out[row][col] += m1[row][inner] * m2[inner][col];
}
}
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment