C++ Online Compiler
Example: Simple Sparse Matrix Transpose in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Simple Sparse Matrix Transpose #include <iostream> #include <vector> // Structure to represent a non-zero element in the sparse matrix struct Term { int row; int col; int value; }; // Structure to represent the sparse matrix itself struct SparseMatrix { int numRows; int numCols; int numTerms; // Number of non-zero elements std::vector<Term> terms; }; // Function to print a sparse matrix void printSparseMatrix(const SparseMatrix& matrix, const std::string& title) { std::cout << title << ":\n"; std::cout << "Rows: " << matrix.numRows << ", Cols: " << matrix.numCols << ", Non-zero terms: " << matrix.numTerms << "\n"; std::cout << "Row\tCol\tValue\n"; for (const auto& term : matrix.terms) { std::cout << term.row << "\t" << term.col << "\t" << term.value << "\n"; } std::cout << "\n"; } // Function to perform simple transpose SparseMatrix simpleTranspose(const SparseMatrix& original) { SparseMatrix transposed; transposed.numRows = original.numCols; // Rows of transpose = Cols of original transposed.numCols = original.numRows; // Cols of transpose = Rows of original transposed.numTerms = original.numTerms; transposed.terms.resize(original.numTerms); // If no non-zero terms, return empty transposed matrix if (original.numTerms == 0) { return transposed; } int k = 0; // Index for transposed matrix terms // Iterate through columns of the original matrix for (int c = 0; c < original.numCols; ++c) { // Iterate through terms of the original matrix for (int i = 0; i < original.numTerms; ++i) { // If the current term belongs to the current column 'c' if (original.terms[i].col == c) { transposed.terms[k].row = original.terms[i].col; // New row is old column transposed.terms[k].col = original.terms[i].row; // New col is old row transposed.terms[k].value = original.terms[i].value; k++; } } } return transposed; } int main() { // Step 1: Define an example sparse matrix // Original 4x5 matrix with 6 non-zero elements // 0 0 0 0 8 // 0 0 0 0 0 // 0 0 3 0 0 // 1 0 0 0 0 SparseMatrix originalMatrix = { 4, // numRows 5, // numCols 6, // numTerms { {0, 4, 8}, {2, 2, 3}, {3, 0, 1}, {0, 0, 10}, // Added for more diverse data {1, 1, 5}, {3, 2, 7} } }; // Step 2: Print the original matrix representation printSparseMatrix(originalMatrix, "Original Sparse Matrix"); // Step 3: Perform simple transpose SparseMatrix transposedMatrix = simpleTranspose(originalMatrix); // Step 4: Print the transposed matrix representation printSparseMatrix(transposedMatrix, "Transposed Sparse Matrix (Simple Transpose)"); return 0; }
Output
Clear
ADVERTISEMENTS