Determinant of a matrix by Gaussian elimination C++ - c++

I was trying to find the code for finding the determinant of a square matrix , and I came across this code.
int det(vector<vector<int> > mat) {
int n = mat.size();
for(int col = 0; col < n; ++col) {
bool found = false;
for(int row = col; row < n; ++row) {
if(mat[row][col]) {
mat[row].swap(mat[col]);
found = true;
break;
}
}
if(!found) {
return 0;
}
for(int row = col + 1; row < n; ++row) {
while(true) {
int del = mat[row][col] / mat[col][col];
for (int j = col; j < n; ++j) {
mat[row][j] -= del * mat[col][j];
}
if (mat[row][col] == 0)
break;
else
mat[row].swap(mat[col]);
}
}
}
li res = 1;
for(int i = 0; i < n; ++i) {
res *= mat[i][i];
}
return abs(res);
}
But I am having trouble understanding line 20-29 i.e where the subtraction of row from multiple of another row is performed. I mean why the while loop is required here ? as I am
subtracting the quotient*dividend , It should always be 0 , right ? So I think it should be just one iteration. So , why we need to perform this mat[row].swap(mat[col]); operation ?
Thanks in advance.

There is some strange logic in your code to account for the fact that you are performing your calculations using integer arithmetic.
Say you have a 3x3 matrix in which the first two rows are:
4 6 5
1 2 3
When you compute del for col=0 and row=1, you will get:
del = 1/4 = 0
With that, when you compute:
mat[row][j] -= del * mat[col][j];
mat[row][j] doesn't change at all.
To account for that, you swap the rows. Now the first two rows are:
1 2 3
4 6 5
With the rows swapped like that, the value of del is 4/1 = 4. Now the line:
mat[row][j] -= del * mat[col][j];
does make a difference. The value of mat[1][0] ends up being zero, which is what you need. So you break out of the while loop.
Here's an instrumented version of your function that produces a lot of debug output, with a helper function to print the matrix and the main function to test the code.
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
void printMatrix(vector<vector<int> > const& mat)
{
int n = mat.size();
for(int row = 0; row < n; ++row) {
for(int col = 0; col < n; ++col) {
cout << mat[row][col] << " ";
}
cout << "\n";
}
cout << "\n";
}
int det(vector<vector<int> > mat) {
int n = mat.size();
for(int col = 0; col < n; ++col) {
cout << "Column: " << col << "\n";
printMatrix(mat);
bool found = false;
for(int row = col; row < n; ++row) {
if(mat[row][col]) {
cout << "Got non-zero value for row " << row << " and col " << col << "\n";
if ( row != col )
{
cout << "(1) Swapping rows " << col << " and " << row << "\n";
mat[row].swap(mat[col]);
printMatrix(mat);
}
else
{
cout << "Not swapping rows\n";
}
found = true;
break;
}
}
if(!found) {
cout << "Did not find a non-zero row. Column: " << col << "\n";
return 0;
}
for(int row = col + 1; row < n; ++row) {
while(true) {
int del = mat[row][col] / mat[col][col];
cout << "del: " << del << "\n";
for (int j = col; j < n; ++j) {
mat[row][j] -= del * mat[col][j];
}
if (mat[row][col] == 0)
{
break;
}
else
{
cout << "(2) Swapping rows " << col << " and " << row << "\n";
mat[row].swap(mat[col]);
printMatrix(mat);
}
}
}
}
printMatrix(mat);
long res = 1;
for(int i = 0; i < n; ++i) {
res *= mat[i][i];
}
return abs(res);
}
int main()
{
vector<vector<int> > mat = { {4, 6, 5}, {1, 2, 3}, {8, 10, 9} };
int r = det(mat);
cout << "Determinant: " << r << endl;
return 0;
}

Related

Having trouble applying sorting to this program

The goal of the program is to generate a multidimensional array, of variable size, the number of columns being the numbers of political parties, the number of rows being the "round" we're in, and the entries of the first row being the number of votes each political party got, then as you get into the second row, round 2, you divide all the values in the first row by 2, in round 3 you divide the values in the first row by 3, and the same thing goes for how many rows the thing has.
I got all that done, but after those operations are over, I want to be able to find the N largest elements, n being the number of rows, and place those elements in a vector, for some reason I can't seem to find, when I run it nothing is displayed on the console, when I get to the part where I want it to sort out the elements, it blacks out, and then crashes.
I've tried changing things around, I don't really think the problem is in the algorithm itself, as I've tried it with static arrays that I've filled randomly, and it sorted those out just fine. Like I said I don't really know where the problem is so I'll show a large part, I've cut out everything not pertinent.
double** ELEITORAL;
void bubble_sort(double** ELEITORAL)
{
int x, y;
double tItem;
int PassCount;
bool Mudou;
for (PassCount = 0; PassCount < (MAX_rows * MAX_columns); PassCount++)
{
//orders the rows
for (y = 0; y < MAX_columns; y++)
{
Mudou = true;
while (Mudou)
{
Mudou = false;
for (x = 1; x < MAX_rows; x++)
{
if (ELEITORAL[x - 1][y] > ELEITORAL[x][y])
{
Mudou = true;
tItem = ELEITORAL[x - 1][y];
ELEITORAL[x - 1][y] = ELEITORAL[x][y];
ELEITORAL[x][y] = tItem;
}
}
}
}
//ORDERS THE COLUMNS
for (x = 0; x < MAX_rows; x++)
{
Mudou = true;
while (Mudou)
{
Mudou = false;
for (y = 1; y < MAX_columns; y++)
{
if (ELEITORAL[x][y - 1] > ELEITORAL[x][y])
{
Mudou = true;
tItem = ELEITORAL[x][y - 1];
ELEITORAL[x][y - 1] = ELEITORAL[x][y];
ELEITORAL[x][y] = tItem;
cout << "entrei";
system("pause");
}
}
}
}
}
}
void DisplayTheArray(double** ELEITORAL)
{
for (int y = 0; y < MAX_columns; y++)
{
for (int x = 0; x < MAX_rows; x++)
{
cout.width(5);
cout << ELEITORAL[x][y];
}
cout << endl;
}
cout << endl;
}
void fill(double **p, int rowsize, int colsize) {
std::cout << std::fixed;
std::cout << std::setprecision(1);
printf("\n Introduza o n%cmero de votos nas listas por ordem \n", 163);
for (int col = 0; col < colsize; col++)
{
cin >> p[row][col];
}
cout << endl;
for (int row = 1; row < rowsize; row++)
{
for (int col = 0; col < colsize; col++)
{
p[row][col] = (p[0][col]/(row + 1));
}
cout << endl; //preenche as linhas
}
}//FILL OUT THE ARRAY
void print(double **p, int rowsize, int colsize)
{
for (int i = 0; i < header.size(); i++) { //HEADER IS TO STORE THE
//NAMES OF THE POLITICAL PARTIES
cout << setw(9) << header[i] << " ";
}
cout << endl;
for (row = 0; row < rowsize; row++) //IMPRIME A MATRIZ EM SI
{
for (col = 0; col < colsize; col++)
{
cout << setw(10) << p[row][col];
}
cout << endl;
}
}//PRINTS THE ARRAY
int MATRIZ()
{
std::cout << std::fixed;
std::cout << std::setprecision(1);
double rows, columns;
printf("\n Qual o n%cmero de candidatos a eleger? \n", 163);
cin >> rows;
printf("\n Qual o n%cmero de listas candidatas? \n", 163);
cin >> columns;
for (i = 0; i < columns; i++)
{
cout << " Qual o nome da lista " << i+1;
cout << endl;
cin >> nomL;
header.push_back(nomL);
}
cout << endl;
system("cls");
ELEITORAL = new double*[rows];
for (int row = 0; row < rows; row++)
{
ELEITORAL[row] = new double[columns];
}
fill(ELEITORAL, rows, columns);
cout << endl;
//After this I have a switch, in case 5 I call the functions
//giving me trouble
case '5':
{
bubble_sort(ELEITORAL);
DisplayTheArray(ELEITORAL);
break;
}
Your display function is sketchy as you assume that the array has MAX dimensions. So my bet would be that your program seg faults due to memory access violation. Please, don't use new, instead use a vector. You won't have to pass the length as a separate parameter and in this case you won't get it wrong. Also double is not appropriate type for indexing, turn on compiler warnings and fix them.
Here's a simple example how can vector be used to make a matrix:
#include <iostream>
#include <vector>
using row_t = std::vector<double>;
using matrix_t = std::vector<row_t>;
//matrix_t = std::vector<std::vector<double>>; Vector of vectors of double
//Pass by reference to avoid copy
//Pass by const if the matrix should be read-only
void printMatrix(const matrix_t& mat)
{
for(auto& row: mat)
for(auto& val: row)
std::cout<<val << ' ';
std::cout<<'\n';//Use this instead of endl if you want just a new line
}
void doubleMatrix(matrix_t& mat)
{
//If you need access to indices during iterating
for(std::size_t r = 0; r < mat.size();++r)
for(std::size_t c = 0; c < mat[r].size();++r)
mat[r][c] *=2.0;
}
int main()
{
std::size_t rows, columns;
std::cin >> rows;
std::cin >> columns;
double fill_value = 0.0;
matrix_t matrix(rows);
//Resize rows to given column width.
for(auto& row: matrix)
row.resize(columns, fill_value);
printMatrix(matrix);
doubleMatrix(matrix);
printMatrix(matrix);
}
Last thing I noticed, If you want to swap two values, use std::swap.

How do I set all the diagonals in a matrix equal to zero?

I have a problem with my homework that asks me to have the compiler print out a matrix in which all the diagonals are outputted as zero. I also have to pass it to a function. However, I have no idea how to do this..
Here is my code:
#include <iostream>
using namespace std;
int diagonals();
int main()
{
//problem 1
int matrix[3][3];
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3 ; j++)
{
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << "\nReverse of the matrix:" << endl;
for (int j = 1; j <= 3; j++)
{
for (int i = 1; i <= 3; i++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}//end of problem 1
//problem 2
cout << "Diagonals changed to 0:\n" << endl;
}
your matrix declaration says int matrix[3][3]; that it has three 1-D array & in each 1-D array you can store three elements. And in C/C++ array index starts from zero.
Problematic statement is for (int i = 1; i <= 3; i++) as you are skipping matrix[0][0] and trying to store into matrix[3][3] which doesn't exist which in turn causes undefined behavior.
So firstly start iterating loop from 0 to number of rows & column respectively.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 ; j++) {
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
Coming to task you mentioned, print out a matrix in which all the diagonals are outputted as zero. ? write one condition so that if row value & col value are equal then assign it to zero otherwise scan from user. Here is the sample code
int main(void) {
int matrix[3][3] = { 0 }; /* initialize it */
int row = sizeof(matrix)/sizeof(matrix[0]); /* find no of rows */
int col = sizeof(matrix[0])/sizeof(matrix[0][0]);/* find no of columns */
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if( i == j)
matrix[i][j] = 0;/* when i and j are equal means thats diagonal and assign it to zero */
else /* if its not diagonal then scan from user */
std::cin>>matrix[i][j];
}
}
return 0;
}
Secondly, I also have to pass it to a function. for this learn how to pass 2d array to a function. Here is the sample example.
void diagonal(int (*mat)[3],int row, int col) { /* mat is pointer to an array */
std::cout<<"printing matrix "<<std::endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
std::cout<<mat[i][j]<<"\t";
}
std::cout<<std::endl;
}
}
And call diagonal() like below from main() function as
diagonal(matrix,row,col); /* pass matrix, no of rows, no of columns */

Finding all saddle points in a matrix c++

I'm working on a code that finds all saddle points in a matrix. Both smallest in their row and biggest in their column, and biggest in their row and smallest in their column fall under the definition (of my university) of a saddle point. Being a beginner I managed to get half of it done (finding saddle points which are smallest in their row and biggest in their column) by copying parts of what we've done in class and typing it myself. I have been stuck on it for quite some time and can't figure how to add the saddle points which are biggest in their row and smallest in their column to the program.
This is what I have so far:
#include <iostream>
#include <cstdlib>
using namespace std;
int a[10][10];
int x, y;
int pos_max(int j) //saddle points check
{
int max = 0;
for (int i = 1; i <= x - 1; i++) {
if (a[i][j] > a[max][j]) {
max = i;
}
}
return max;
}
int main() {
cout << "Enter the number of rows: ";
cin >> x;
cout << "Enter the number of columns: ";
cin >> y;
cout << "----------------------------" << endl;
for (int i = 0; i <= x - 1; i++) //input of the matrix
for (int j = 0; j <= y - 1; j++) {
cout << "a[" << i + 1 << ", " << j + 1 << "] = ";
cin >> a[i][j];
}
cout << "----------------------------\n";
for (int i = 0; i <= x - 1; i++) //visualization of the matrix
{
for (int j = 0; j <= y - 1; j++)
cout << a[i][j] << " ";
cout << endl;
}
cout << "----------------------------\n";
int r;
int flag = 0;
int i = y;
for (int j = 0; j <= y - 1; j++) {
r = pos_max(j);
for (i = 0; i <= y - 1; i++) {
if (a[r][i] < a[r][j]) {
break;
}
}
if (i == y) {
cout << "Saddle points are: ";
cout << "a[" << r + 1 << ", " << j + 1 << "] = " << a[r][j] << "\n";
flag = 1;
}
}
if (flag == 0) {
cout << "No saddle points\n";
}
cout << "----------------------------\n";
return 0;
}
First, there is a logical error with your code. In the pos_max function, it will return the index of the element which is maximum in the column. There can be a case when there are multiple maximum with the same value in the column, however, it returns the one which is not the minimum in the row, hence your program won't be able to print that saddle point.
To solve this, you can either return an array of all indices which are maximum in a column and then check for each of those points if it's minimum in their respective column, but I think it's not a very elegant solution. In any case, you will again have to write the entire code for the other condition for saddle points, minimum in column and maximum in row.
Hence, I would suggest a change in strategy. You create 4 arrays, max_row, max_col, min_row, min_col, where each array stores the minimum / maximum in that row / column respectively. Then you can traverse the array and check if that point satisfies saddle point condition.
Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int a[10][10];
int max_row[10], max_col[10], min_row[10], min_col[10];
int x, y;
bool is_saddle(int i, int j) {
int x = a[i][j];
return (max_row[i] == x && min_col[j] == x) || (min_row[i] == x && max_col[j] == x);
}
int main() {
/* code to input x, y and the matrix
...
*/
/* code to visualize the matrix
...
*/
/* populating max and min arrays */
for (int i = 0; i <= x-1; ++i) {
max_row[i] = a[i][0], min_row[i] = a[i][0];
for (int j = 0; j <= y-1; ++j) {
max_row[i] = max(max_row[i], a[i][j]);
min_row[i] = min(min_row[i], a[i][j]);
}
}
for (int j = 0; j <= y-1; ++j) {
max_col[j] = a[0][j], min_col[j] = a[0][j];
for (int i = 0; i <= x-1; ++i) {
max_col[j] = max(max_col[j], a[i][j]);
min_col[j] = min(min_col[j], a[i][j]);
}
}
/* Check for saddle point */
for (int i = 0; i <= x-1; ++i) {
for (int j = 0; j <= y-1; ++j) {
if (is_saddle(i, j)) {
cout << "Saddle points are: ";
cout << "a[" << i + 1 << ", " << j + 1 << "] = " << a[i][j] << "\n";
flag = 1;
}
}
}
if (flag == 0) {
cout << "No saddle points\n";
}
cout << "----------------------------\n";
return 0;
}
#include <iostream>
using namespace std;
int getMaxInRow(int[][5], int, int, int);
int getMinInColumn(int[][5], int, int, int);
void getSaddlePointCordinates(int [][5],int ,int );
void getInputOf2dArray(int a[][5], int, int);
int main()
{
int a[5][5] ;
int rows, columns;
cin >> rows >> columns;
getInputOf2dArray(a, 5, 5);
getSaddlePointCordinates(a,rows,columns);
}
void getInputOf2dArray(int a[][5], int rows, int columns)
{
for (int i = 0; i < rows; i = i + 1)
{
for (int j = 0; j < columns; j = j + 1)
{
cin >> a[i][j];
}
}
}
void getSaddlePointCordinates(int a[][5],int rows,int columns)
{
int flag = 0;
for (int rowNo = 0; rowNo < 5; rowNo++)
{
for (int columnNo = 0; columnNo < 5; columnNo++)
{
if (getMaxInRow(a, rows, columns, rowNo) == getMinInColumn(a, rows, columns, columnNo))
{
flag = 1;
cout << rowNo << columnNo;
}
}
}
if (flag == 0)
cout << "no saddle point";
cout << "\n";
}
int getMaxInRow(int a[][5], int row, int column, int rowNo)
{
int max = a[rowNo][0];
for (int i = 1; i < column; i = i + 1)
{
if (a[rowNo][i] > max)
max = a[rowNo][i];
}
return max;
}
int getMinInColumn(int a[][5], int row, int column, int columnNo)
{
int min = a[0][columnNo];
for (int i = 1; i < row; i = i + 1)
{
if (a[i][columnNo] < min)
min = a[i][columnNo];
}
return min;
}
just take the reference arr(ref[size]) // memorization method to check the minimum and maximum value in it.
Here is the Code Implementation with time complexity O(n *n) & space complexity O(n):
#include <bits/stdc++.h>
using namespace std;
#define size 5
void util(int arr[size][size], int *count)
{
int ref[size]; // array to hold all the max values of row's.
for(int r = 0; r < size; r++)
{
int max_row_val = arr[r][0];
for(int c = 1; c < size; c++)
{
if(max_row_val < arr[r][c])
max_row_val = arr[r][c];
}
ref[r] = max_row_val;
}
for(int c = 0; c < size; c++)
{
int min_col_val = arr[0][c];
for(int r = 1; r < size; r++) // min_val of the column
{
if(min_col_val > arr[r][c])
min_col_val = arr[r][c];
}
for(int r = 0; r < size; r++) // now search if the min_val of col and the ref[r] is same and the position is same, if both matches then print.
{
if(min_col_val == ref[r] && min_col_val == arr[r][c])
{
*count += 1;
if((*count) == 1)
cout << "The cordinate's are: \n";
cout << "(" << r << "," << c << ")" << endl;
}
}
}
}
// Driver function
int main()
{
int arr[size][size];
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
cin >> arr[i][j];
}
int count = 0;
util(arr, &count);
if(!count)
cout << "No saddle points" << endl;
}
// Test case -> Saddle Point
/*
Input1:
1 2 3 4 5
6 7 8 9 10
1 2 3 4 5
6 7 8 9 10
0 2 3 4 5
Output1:
The cordinate's are:
(0,4)
(2,4)
(4,4)
Input2:
1 2 3 4 5
6 7 8 9 1
10 11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Output2:
No saddle points
*/

Two-Dimensional Array Searching Algorithm Optimisation

I have been given a "Sand box" of variable length and width. I've been given instructions to find a "shovel" of static size, which may be oriented either horizontally or vertically. I implement the following algorithm in order to search the least amount of times to find one valid location (one which corresponds to a "part of the object") in the grid:
found = false;
nShift = 0;
shovelSize = 4;
for(int i = 0; i < SandBoxRows; i++) {
for(int j = 0; j < SandBoxColumns; j+=shovelSize) {
found = probeSandBoxTwo(('A' + i), (j + 1 + nShift));
}
if(nShift >= shovelSize - 1 || nShift > SandBoxColumns) {
nShift = 0;
} else {
nShift++;
}
}
In this case, the "Sand box" will be tested by the function as described below.
I completely recreate this scenario with a "Sand box" whose size is fixed (though easily manipulated) whose shovel is still randomly placed and oriented within the following code:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
const int ROW = 12;
const int COL = 16;
char sandbox[ROW][COL];
bool probeSandBoxTwo(char c, int i);
void displayResults(int sCount, bool found, int x, int y);
void displaySandbox();
void displaySearchPattern();
void fillSandbox();
void placeShovel();
int main() {
fillSandbox();
placeShovel();
displaySandbox();
//define your variables here
bool found;
int nShift,
sCount,
shovelSize,
x,
y;
found = false;
nShift = 0;
shovelSize = 4;
sCount = 0;
for(int i = 0; i < ROW && !found; i++) {
for(int j = 0; j < COL && !found; j+=shovelSize) {
found = probeSandBoxTwo(('A' + i), (j + 1 + nShift));
x = i;
y = j + nShift;
sCount++;
cout << "Search conducted at (" << i << ", " << (j + nShift) << ")" << endl;
}
if(nShift >= shovelSize - 1 || nShift > ROW) {
nShift = 0;
} else {
nShift++;
}
}
displayResults(sCount, found, x, y);
displaySearchPattern();
}
bool probeSandBoxTwo(char c, int i) {
if(sandbox[c-'A'][i-1] == 'X') {
return true;
} else {
return false;
}
}
void displayResults(int sCount, bool found, int x, int y) {
cout << endl;
cout << "Total searches: " << sCount << endl;
cout << endl;
if(found) {
cout << "Shovel found at coordinates: (" << x << ", " << y << ")" << endl;
}
}
void displaySandbox() {
cout << " ";
for(int i = 0; i < COL; i++) {
cout << (i % 10); //show index numbers [col]
}
cout << endl;
for(int i = 0; i < ROW; i++) {
cout << (i % 10) << " "; //show index numbers [row]
for(int j = 0; j < COL; j++) {
cout << sandbox[i][j];
}
cout << endl;
}
cout << endl;
}
void displaySearchPattern() {
int nShift = 0;
int shovelSize = 4;
cout << endl << " ";
for(int i = 0; i < COL; i++) {
cout << (i % 10); //show index numbers [col]
}
cout << endl;
for(int i = 0; i < ROW; i++) {
cout << (i % 10) << " "; //show index numbers [row]
for(int j = 0; j < COL; j++) {
if(!((j + nShift) % shovelSize)) {
cout << 'o';
} else {
cout << '.';
}
}
if(nShift >= shovelSize - 1 || nShift > COL) {
nShift = 0;
} else {
nShift++;
}
cout << endl;
}
}
void fillSandbox() {
for(int i = 0; i < ROW; i++) {
for(int j = 0; j < COL; j++) {
sandbox[i][j] = '.';
}
}
}
void placeShovel() {
srand(time(NULL));
int shovelRow,
shovelCol,
shovelSize = 4;
if(rand() % 2) {
//horizontal
shovelRow = rand() % ROW + 1;
shovelCol = rand() % (COL - (shovelSize - 1)) + 1;
for(int i = shovelCol - 1; i < shovelSize + (shovelCol - 1); i++) {
sandbox[shovelRow - 1][i] = 'X';
}
} else {
//vertical
shovelRow = rand() % (ROW - (shovelSize - 1)) + 1;
shovelCol = rand() % COL + 1;
for(int i = shovelRow - 1; i < shovelSize + (shovelRow - 1); i++) {
sandbox[i][shovelCol - 1] = 'X';
}
}
}
In this code, I also graphically display the pattern (when run) with which my algorithm searches.
Is this truly the optimal search pattern for such a scenario, is my implementation correct, and if so, why might I be having incorrect results returned?
A given test driver reports the following results:
The source code for this result (and its test driver).
found = false;
nShift = 0;
shovelSize = 4;
for(int i = 0; i < SandBoxRows; i++) {
for(int j = 0; (j + nShift) < SandBoxColumns; j+=shovelSize) {
found = probeSandBoxTwo(('A' + i), (j + 1 + nShift));
}
if(nShift >= shovelSize - 1 || nShift > SandBoxColumns) {
nShift = 0;
} else {
nShift++;
}
}
This corrects an error in the conditional portion of the for loop header which did not account for the index-shifting variable nShift.

How to Sum Column of a Matrix and Store it in a Vector in C++

Is there a straight forward way to do it?
I'm stuck here:
#include <iostream>
#include <vector>
#include <cstdlib>
using std::size_t;
using std::vector;
int main()
{
vector<vector<int> > Matrix;
//Create the 2x2 matrix.
size_t rows = 2;
size_t cols = 2;
// 1: set the number of rows.
Matrix.resize(rows);
for(size_t i = 0; i < rows; ++i)
{
Matrix[i].resize(cols);
}
// Create Matrix
Matrix[0][0] = 1;
Matrix[0][1] = 2;
Matrix[1][0] = 3;
Matrix[1][1] = 4;
// Create Vector to store sum
vector <int> ColSum;
for(size_t i = 0; i < rows; ++i)
{
for(size_t j = 0; j < cols; ++j)
{
std::cout <<"["<<i<<"]"<<"["<<j<<"] = " <<Matrix[i][j]<<std::endl;
// I'm stuck here
}
}
return 0;
}
Given the matrix above:
1 2
3 4
In the end we hope to print the result of a vector
(that keeps the sum of each column):
4 6
Note that the matrix can be of any dimension.
for( size_t row = 0; row < Matrix.size(); row++ )
{
ColSum[row] = 0;
for( size_t column = 0; column < Matrix[row].size(); column++ )
{
ColSum[row] += Matrix[row][column];
}
}
// Create Vector to store sum
vector <int> ColSum;
ColSum.Resize(cols);
for(size_t i = 0; i < rows; ++i)
{
for(size_t j = 0; j < cols; ++j)
{
std::cout <<"["<<i<<"]"<<"["<<j<<"] = " <<Matrix[i][j]<<std::endl;
ColSum[j] += Matrix[i][j];
}
}
This should work. At the end, you will have sums in ColSum
vector <int> ColSum;
ColSum.resize(cols);
for(size_t j = 0; j < cols; ++j)
{
int sum = 0;
for(size_t i = 0; i < rows; ++i)
{
sum += Matrix[i][j];
}
ColSum[j] = sum;
}
#include <iostream.h>
#include <conio.h>
int main()
{
int A[10][10],m,n,x,y,sum=0;
//Create a Matrix A
cout << "Enter number of rows and columns in Matrix A : \n";
cin>>n>>m;
cout << "Enter elements of Matrix A : \n";
for(x=1;x<n+1;++x)
for(y=1;y<m+1;++y)
cin>>A[x][y];
//Find sum of each row
for(x=1;x<n+1;++x)
{
A[x][m+1]=0;
for(y=1;y<m+1;++y)
A[x][m+1]=A[x][m+1]+A[x][y];
}
//Find sum of each column
for(y=1;y<m+1;++y)
{
A[n+1][y]=0;
for(x=1;x<n+1;++x)
A[n+1][y]+=A[x][y];
}
cout << "\nMatrix A, Row Sum (Last Column)" << " and Column Sum (Last Row) : \n";
for(x=1;x<n+1;++x)
{
for(y=1;y<m+2;++y)
cout << A[x][y] << " ";
cout << "\n";
}
//Print sum of each column
x=n+1;
for(y=1;y<m+1;++y)
cout << A[x][y] << " ";
cout << "\n";
if(m==n)
{
for(x=1;x<m+1;x++)
for(y=1;y<n+1;y++)
if(x==y)
sum+=A[x][y];
else
if(y==m-(x+1))
sum+=A[x][y];
}
cout << "Sum of diagonal elements is : " << sum << endl;
getch();
return 0;
}