用java语言实现一个类Matrix,用来表示矩阵,所实现的类应该支持下面的操作:
●根据给定的行和列的数目创建一个矩阵。
●在某个给定的行和列的位置上取得或设置元素c
●对两个相容的矩阵进行相加和相乘运算:
并提供一个相应的测试程序。

解决方案 »

  1.   

    //用java语言实现一个类Matrix,用来表示矩阵,所实现的类应该支持下面的操作:
    //●根据给定的行和列的数目创建一个矩阵。
    //●在某个给定的行和列的位置上取得或设置元素c
    //●对两个相容的矩阵进行相加和相乘运算:
    //并提供一个相应的测试程序。class Matrix
    {
    private int[][] element;
    public int x,y;
    Matrix(int x,int y)
    {
    this.x=x;
    this.y=y;
    element=new int[x][y];
    }
    public int getElement(int x,int y)
    {
    return element[x][y];
    }
    public void setElement(int val,int x,int y)
    {
    element[x][y]=val;
    }

    public Matrix addition(Matrix _mat)
    {
    Matrix matBuf=new Matrix(x,y);
    for(int fx=0;fx<x;fx++)
    {
    for(int fy=0;fy<y;fy++)
    {
    int buf=this.getElement(fx,fy)+_mat.getElement(fx,fy);
    matBuf.setElement(buf,fx,fy);
    }

    }
    return matBuf;
    }
    public Matrix multiplication(Matrix _mat)
    {
    Matrix matBuf=new Matrix(this.x,_mat.y);
    for(int fx=0;fx<matBuf.x;fx++)
    {
    for(int fy=0;fy<matBuf.y;fy++)
    {
    int buf=0;
    for(int i=0;i<this.y;i++)
    {
    buf=buf+this.getElement(fx,i)*_mat.getElement(i,fy);
    }
    matBuf.setElement(buf,fx,fy);
    }
    }
    return matBuf;
    }
    public void printer()
    {

    for(int fx=0;fx<x;fx++)
    {
    for(int fy=0;fy<y;fy++)
    {
    System.out.print(this.getElement(fx,fy)+"-");
    }
    System.out.println();

    }
    System.out.println();
    }
    }public class Test4
    { /**
     * @param args
     */

    public static void main(String[] args)
    {
    // TODO 自动生成方法存根
    Matrix mat1=new Matrix(3,4);
    Matrix mat2=new Matrix(3,4);
    Matrix mat3=new Matrix(4,3);
    for(int fx=0;fx<3;fx++)
    {
    for(int fy=0;fy<4;fy++)
    {
    int buf=fx+fy;
    mat1.setElement(buf,fx,fy);
    mat2.setElement(buf,fx,fy);
    mat3.setElement(buf,fy,fx);
    }


    }
    System.out.println("mat1 mat2:");
    mat1.printer();
    System.out.println("mat3:");
    mat3.printer();
    System.out.println("mat1+mat2:");
    mat1.addition(mat2).printer();
    System.out.println("mat1*mat3:");
    mat1.multiplication(mat3).printer();


    }}
    ------------------
    得到结果
    mat1 mat2:
    0-1-2-3-
    1-2-3-4-
    2-3-4-5-mat3:
    0-1-2-
    1-2-3-
    2-3-4-
    3-4-5-mat1+mat2:
    0-2-4-6-
    2-4-6-8-
    4-6-8-10-mat1*mat3:
    14-20-26-
    20-30-40-
    26-40-54-