如何总结矩阵的列并将其存储在C++中的向量中
问题描述:
有没有一种简单的方法可以做到这一点? 我被困在这里:如何总结矩阵的列并将其存储在C++中的向量中
#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;
}
鉴于上述矩阵:
1 2
3 4
在我们希望打印矢量 (即保持每列的总和)的结果结束:
4 6
请注意,矩阵可以是任何维度。
答
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];
}
}
答
这应该工作。最后,你将有资金在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;
}