shawn.bug 2008-11-07 21:21
浏览 270
已采纳

用数组实现矩阵相乘的问题

矩阵相乘有点迷糊
帮忙做下,越简单越好,能实现就OK

设计和编写代表矩阵的Matrix类。该类包括矩阵行列数变量int rows和int cols,矩阵数据数组double data[][],构造方法Matrix()、Matrix(int rows,int cols)、Matrix(int rows,int cols,double data[][]),获取某元素值的方法getData(int row,int col),设置某元素值的方法setData(int row,int col,double value),计算两个矩阵的乘积的方法multiply(Matrix m)以及toString()等内容。

  • 写回答

4条回答 默认 最新

  • sptzone 2008-11-07 22:06
    关注

    [code="java"]public class Matrix {
    int rows;
    int cols;
    double data[][];

    public Matrix() {
        this(0, 0);
    }
    
    public Matrix(int rows, int cols) {
        this(rows, cols, new double[rows][cols]);
    }
    
    public Matrix(int rows, int cols, double[][] data) {
        super();
        this.rows = rows;
        this.cols = cols;
        this.data = data;
    }
    
    public double getData(int row, int col) {
        return data[row][col];
    }
    
    public void setData(int row, int col, double value) {
        data[row][col] = value;
    }
    
    public double[][] multiply(double[][] m2) {
        int m1rows = data.length;
        int m1cols = data[0].length;
        int m2rows = m2.length;
        int m2cols = m2[0].length;
        if (m1cols != m2rows)
            throw new IllegalArgumentException("matrix doesn't match");
        double[][] result = new double[m1rows][m2cols];
    
        // multiply
        for (int i = 0; i < m1rows; i++)
            for (int j = 0; j < m2cols; j++)
                for (int k = 0; k < m1cols; k++)
                    result[i][j] += data[i][k] * m2[k][j];
    
        return result;
    }
    
    public String toString() {
        StringBuffer sb = new StringBuffer();
    
        int rows = data.length;
        int cols = data[0].length;
    
        sb.append("array[" + rows + "][" + cols + "] = " + "\n");
        for (int i = 0; i < rows; i++) {
    
            for (int j = 0; j < cols; j++)
                sb.append(" " + data[i][j] + " ");
            sb.append("\n");
        }
        sb.append("\n");
    
        return sb.toString();
    }
    
    public static void main(String[] argv) {
    
        double x[][] = { { 3, 2, 3 }, { 5, 9, 8 }, };
        Matrix m = new Matrix(3, 2, x);
    
        double y[][] = { { 4, 7 }, { 9, 3 }, { 8, 1 }, };
    
        double z[][] = m.multiply(y);
    
        Matrix zm = new Matrix(z.length, z[0].length, z);
    
        // print result
        System.out.println(zm);
    }
    

    }[/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。