C++矩阵和向量之间的操作

进行数据分析时,常需要显示矩阵和向量,以及取出矩阵的某一行或者某一列并将它存成向量,或将向量存到矩阵的某一列或某一行。以下程序展示了这类操作:

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

const int M = 4;
const int N = 5;
void ShowMatrix(double A[][N]);
void ShowVector(double A[]);
void PickRow(double A[][N], double B[], int S);
void SetCol(double A[][N], double B[], int S);

int _tmain(int argc, _TCHAR* argv[])
{
	
	double M2D[M][N];
	double PickV[N];
	double Data[] = { 1.3, 4.5, 8.32, 45.9, 0.4 };
	int PRow = 1; int SRow = 2;
	for (int i = 0; i < M;i++)
	{
		for (int j = 0; j < N;j++)
		{
			M2D[i][j] = (i + j*j + 0.5) / (i + j + 2);
		}
	}
	cout << "原来的矩阵是:\n";
	ShowMatrix(M2D);
	cout << "原来的向量Data是:\n";
	ShowVector(Data);
	cout << "将矩阵的第" << PRow + 1
		<< "行取出成向量PickV:\n";
	PickRow(M2D, PickV,PRow);
	ShowVector(PickV);
	cout << "将矩阵的第" << SRow + 1
		<< "行以向量Data取代后,\n矩阵称为:\n";
	SetCol(M2D, Data, SRow);
	ShowMatrix(M2D);
	return 0;
}

void ShowMatrix(double A[][N])
{
	cout << setprecision(4) << right << showpoint << fixed;
	for (int i = 0; i < M; i++)
	{
		cout << "第"<<i + 1<<"行:";
		for (int j = 0; j < N;j++)
		{
			cout << setw(8) << A[i][j] << " ";
		}
		cout << endl;
	}
	cout << endl;
}

void ShowVector(double A[])
{
	cout << setprecision(4) << right
		<< showpoint << fixed;
	cout << "向量: ";
	for (int j = 0; j < N;j++)
	{
		cout << setw(8) << A[j] << " ";
	}
	cout << endl;
	cout << endl;
}

void PickRow(double A[][N], double B[], int S)
{
	for (int i = 0; i < N;i++)
	{
		B[i] = A[S][i];
	}
	return;
}

void SetCol(double A[][N], double B[], int S)
{
	for (int j = 0; j < N;j++)
	{
		A[S][j] = B[j];
	}
	return;
}
输出结果:

C++矩阵和向量之间的操作_第1张图片

你可能感兴趣的:(C++矩阵和向量之间的操作)