Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include"SparseMatrix.h"
- void SparseMatrix::setAt(unsigned row, unsigned col, double val) {
- rangeCheck(row, col);
- // YOUR CODE HERE
- unsigned index = row * ncol + col;
- if (val == 0)
- return;
- Element e;
- e.row = row;
- e.col = col;
- e.val = val;
- if (size == 0) { //moi khoi tao mang
- add(e);
- return;
- }
- else { //mang co it nhat 1 element
- for (int i = 0; i < size; i++) {
- int idx1D = (storage[i].row* ncol + storage[i].col);
- if (idx1D > index) {
- insertAt(i, e);
- return;
- }
- else if (idx1D == index) {
- storage[i].val = val;
- return;
- }
- }
- add(e);
- }
- }
- double SparseMatrix::getAt(unsigned row, unsigned col) {
- rangeCheck(row, col);
- // YOUR CODE HERE
- for (int i = 0; i < size; i++) {
- if (row == storage[i].row && col == storage[i].col) {
- return storage[i].val;
- }
- }
- return 0;
- }
- SparseMatrix* SparseMatrix::transpose() {
- SparseMatrix* result = NULL;
- // YOUR CODE HERE
- for (int i = 0; i < size; i++) {
- Element temp;
- temp.row = storage[i].col;
- temp.col = storage[i].row;
- temp.val = storage[i].val;
- result->add(temp);
- }
- return result;
- }
- double SparseMatrix::trace() {
- if (nrow != ncol)
- throw "TraceOfNoneSquareMatrix";
- double result = 0;
- // YOUR CODE HERE
- for (int i = 0; i < size; i++)
- if (storage[i].col == storage[i].row)
- result += storage[i].val;
- return result;
- }
- SparseMatrix* SparseMatrix::add(const SparseMatrix& b) {
- if(nrow != b.nrow || ncol != b.ncol)
- throw "MismatchedDimensions";
- SparseMatrix* result = new SparseMatrix(b);
- // YOUR CODE HERE
- for (int i = 0; i < nrow; i++) {
- for (int j = 0; j < ncol; j++) {
- result->setAt(i, j, getAt(i, j) + result->getAt(i,j));
- }
- }
- return result;
- }
- SparseMatrix* SparseMatrix::multiplyPointWise(const SparseMatrix& b) {
- if (nrow != b.nrow || ncol != b.ncol)
- throw "MismatchedDimensions";
- SparseMatrix* result = new SparseMatrix(b);
- // YOUR CODE HERE
- for (int i = 0; i < size; i++)
- for (int j = 0; j < b.size; j++)
- if (storage[i].col == b.storage[j].col && storage[i].row == b.storage[j].row)
- result->setAt(storage[i].row, storage[i].col, storage[i].val*b.storage[j].val);
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement