⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 matrix.cpp

📁 DFP变尺度法
💻 CPP
字号:
//CMatrix.cpp
#include<stdlib.h>
#include<math.h>
#include "matrix.h"

CMatrix::CMatrix(int row,int col)
{
	CMatrix::row=row;
	CMatrix::col=col;
	elem=new double[row*col];
	for(int i=0;i<row*col;i++)
		elem[i]=0.0;
}

void CMatrix::set(int row,int col)
{
	CMatrix::row=row;
	CMatrix::col=col;
	elem=new double[row*col];
	for(int i=0;i<row*col;i++)
		elem[i]=0.0;
}

CMatrix::CMatrix(const CMatrix& m):row(m.row),col(m.col)
{
	elem=new double[m.row*m.col];
	for(int i=0;i<=row*col;i++)
		elem[i]=m.elem[i];
}

CMatrix& CMatrix::operator =(const CMatrix& m)
{
	row=m.row,col=m.col;
	if (this!=&m)
	{
		delete[] elem;
		elem=new double[row*col];
		for(int i=0;i<=row*col;i++)
			elem[i]=m.elem[i];
	}
	return *this;
}

double& CMatrix::operator()(int x, int y) 
{
	return elem[col*(x-1)+y-1];
}

double CMatrix::operator()(int x, int y) const
{
	return elem[col*(x-1)+y-1];
}

double CMatrix::getmod()
{
	if(col!=1){
		cerr<<"不是列向量(不能求模) \n";
		exit(1);
	}
	double temp=0;
	for (int i=1;i<=row ;i++)
		temp+=operator()(i,1)*operator()(i,1);
    double mod=sqrt(temp);
	return mod;
}

double CMatrix::mult(const CMatrix& b)
{
	if (col!=b.row)
	{
		cerr<<"the two CMatrix can't be multiplied \n";
		exit(1);
	}
	double temp=0;
	for(int i=1;i<=col;i++)
		temp+=operator()(1,i)*b(i,1);
	return temp;
}

CMatrix CMatrix::invert()
{
	CMatrix temp(col,row);
	for(int i=1;i<=row;i++)
	{
		for(int j=1;j<=col;j++)
		{
			temp(j,i)=operator()(i,j);
		}
	}
	return temp;
}
	
CMatrix operator +(const CMatrix& a, const CMatrix& b)
{
	if (a.col!=b.col || a.row!=b.row)
	{
		cerr<<"the tow CMatrix can't be added \n"; 
		exit(1);
	}
	CMatrix temp(a.row,a.col);
	for (int i=1; i<=a.row; i++)
	{
		for (int j=1; j<=a.col; j++)
		{
		temp(i,j)=a(i,j)+b(i,j);
		}
	}
	return temp;
}

CMatrix operator -(const CMatrix& a, const CMatrix& b)
{
	return a+(-1.0*b);
}

CMatrix operator *(const CMatrix& a, const CMatrix& b)
{
	if (a.col!=b.row)
	{
		cerr<<"the two CMatrix can't be multiplied \n";
		exit(1);
	}
	CMatrix temp(a.row,b.col);
	for(int i=1;i<=a.row;i++)
	{
		for(int j=1;j<=b.col;j++)
		{
			for (int n=1;n<=a.row;n++)
			{
				temp(i,j)+=a(i,n)*b(n,j);
			}
		}
	}
	return temp;
}

CMatrix operator * (double a,const CMatrix& b)
{
	CMatrix temp(b.row ,b.col);
	for(int i=1;i<=b.row;i++)
	{
		for(int j=1;j<=b.col;j++)
		{
			temp(i,j)=a*b(i,j);
		}
	}
	return temp;
}

CMatrix operator/(const CMatrix& b,double a)
{
	return (1/a)*b;
}

ostream& operator<<(ostream& out, const CMatrix& a)
{
	for(int i=1;i<=a.row;i++)
	{
		for (int j=1;j<=a.col;j++)
		{
			out<<a(i,j)<<"  ";
		}
		cout<<endl;
	}
	return out;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -