0% found this document useful (0 votes)
32 views

Fast Transpose Sparse Matrix

Uploaded by

Impana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Fast Transpose Sparse Matrix

Uploaded by

Impana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

ii.

) To find the fast transpose of the sparse matrix

#include <stdio.h>

#define MAX 100

struct SparseMatrix {

int row, col, value;

};

void fastTranspose(struct SparseMatrix mat[], struct SparseMatrix trans[]) {

int rowTerms[MAX] = {0}, startPos[MAX], numTerms = mat[0].value;

for (int i = 1; i <= numTerms; i++)

rowTerms[mat[i].col]++;

startPos[0] = 1;

for (int i = 1; i < mat[0].col; i++)

startPos[i] = startPos[i - 1] + rowTerms[i - 1];

for (int i = 1; i <= numTerms; i++) {

int pos = startPos[mat[i].col]++;

trans[pos].row = mat[i].col;

trans[pos].col = mat[i].row;

trans[pos].value = mat[i].value;

trans[0].row = mat[0].col;

trans[0].col = mat[0].row;

trans[0].value = numTerms;

void printMatrix(struct SparseMatrix mat[]) {

for (int i = 0; i <= mat[0].value; i++)

printf("%d\t%d\t%d\n", mat[i].row, mat[i].col, mat[i].value);

int main() {

struct SparseMatrix mat[MAX] = {{3, 3, 3}, {0, 0, 1}, {1, 1, 2}, {2, 2, 3}};

struct SparseMatrix trans[MAX];

printf("Original Matrix:\n");
printMatrix(mat);

fastTranspose(mat, trans);

printf("\nTransposed Matrix:\n");

printMatrix(trans);

return 0;

OUTPUT:

ALGORITHM:

Step 1:start

Step 2: Input the sparse matrix

Read the matrix's dimensions and non-zero elements from the user.

Step 3: Initialize row-term counting array

Create an array rowTerms[] to store the count of how many non-zero elements are present in each
column of the matrix.

Step 4: Count the number of elements in each column

Traverse the sparse matrix and count how many non-zero elements are in each column.

Step 5: Calculate starting positions for each column

Compute the starting positions for each column in the transposed matrix using the rowTerms[] array
and store them in the startPos[] array. The first column starts at index 1 (ignoring 0).

Step 6: Place elements in transposed positions


For each non-zero element in the original matrix, use the startPos[] array to place it in the
transposed matrix in the correct position. Adjust startPos[] after placing each element

Step 7:stop.

You might also like