添加矩阵

huangapple go评论65阅读模式
英文:

Adding Matrices

问题

在这个程序中,我试图创建一个新的方法,可以将两个创建的矩阵相加。为了实现这一点,我需要检查这些矩阵是否具有相同的维度,然后输出相加后的矩阵。这些矩阵中填充有在代码中设置的随机数。有人可以帮助我创建一个能够将两个矩阵相加的方法吗?

public class Matrix {
    private int [][] grid;  
    
    /**
     * default constructor: creates 3x3 matrix with random values
     * in the range 0..9
     */
    public Matrix() {
        grid = new int[3][3];
        for(int x=0; x<3; x++)
            for(int y=0; y<3; y++)
                grid[x][y] = (int)(Math.random()*10);
    }
    
    /**
     * Creates matrix of specified size with random values 0..9
     * @param size positive integer that represents the number of rows
     * and columns in the matrix
     */
    public Matrix(int size) {
        grid = new int[size][size];
        for(int x=0; x<size; x++)
            for(int y=0; y<size; y++)
                grid[x][y] = (int)(Math.random()*10);
    }
    
    /** 
     * Creates a matrix of specified size with random values 0..9
     * @param rows number of rows in matrix
     * @param columns number of columns int matrix
     */
    public Matrix(int rows, int columns) {
        grid = new int[rows][columns];
        for(int x=0; x<rows; x++)
            for(int y=0; y<columns; y++)
                grid[x][y] = (int)(Math.random()*10);
    }
    
    /**
     * @return String formatted as an m x n matrix of m rows and 
     * n columns
     */
    public String toString() {
        int rows = grid.length;
        int columns = grid[0].length;
        String table = new String("");
        for(int x=0; x<rows; x++) {
            table = table + '|' + '\t';
            for(int y=0; y<columns; y++)
                table = table + grid[x][y] + '\t';
            table = table + '|' + '\n';
        }
        return table;
    }
    
    /**
     * @return true if number of rows equals number of columns
     */
    public boolean isSquare() {
        return grid.length == grid[0].length;
    }
    
    /**
     * @param other another matrix to compare to this one
     * @return true if this matrix and the other have the same
     * number of rows and columns
     */
    public boolean sameSize(Matrix other) {
        return grid.length == other.grid.length && 
                grid[0].length == other.grid[0].length;
    }
    
    /**
     * Adds another matrix to this matrix
     * @param other the matrix to be added
     * @return a new matrix that is the sum of this matrix and the other matrix
     */
    public Matrix add(Matrix other) {
        if (!sameSize(other)) {
            throw new IllegalArgumentException("Matrices must have the same dimensions to be added.");
        }
        
        int rows = grid.length;
        int columns = grid[0].length;
        Matrix result = new Matrix(rows, columns);
        
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < columns; y++) {
                result.grid[x][y] = this.grid[x][y] + other.grid[x][y];
            }
        }
        
        return result;
    }
    
    // main method: for testing
    public static void main(String[] args) {
        Matrix m = new Matrix();
        Matrix n = new Matrix((int)(Math.random()*5)+2);
        Matrix o = new Matrix(((int)(Math.random()*5)+2),
                            ((int)(Math.random()*5)+2));
        System.out.println ("First matrix:");
        System.out.print(m);
        System.out.println ("Second matrix:");
        System.out.println(n);
        System.out.println ("Third matrix:");
        System.out.println(o);
        if(m.sameSize(n))
            System.out.println("First two are the same size");
        else
            System.out.println("First two are not the same size");
        if(o.isSquare())
            System.out.println("All three are square matrices");
        else
            System.out.println("Only first two are square matrices");
        
        Matrix sumMatrix = m.add(n);
        System.out.println("Sum of the first and second matrix:");
        System.out.println(sumMatrix);
    }
}
英文:

In this program I am attempting to create a new method that can add two of the matrices that are created. In order to do this I need to check to see if the matrices have the same dimensions and then print out the added matrices. The matrices are filled with random numbers that are set in the code. Can someone help create a method that will allow me to add two of them together?

public class Matrix {
private int [][] grid;  
/**
* default constructor: creates 3x3 matrix with random values
* in the range 0..9
*/
public Matrix() {
grid = new int[3][3];
for(int x=0; x&lt;3; x++)
for(int y=0; y&lt;3; y++)
grid[x][y] = (int)(Math.random()*10);
}
/**
* Creates matrix of specified size with random values 0..9
* @param size positive integer that represents the number of rows
* and columns in the matrix
*/
public Matrix(int size) {
grid = new int[size][size];
for(int x=0; x&lt;size; x++)
for(int y=0; y&lt;size; y++)
grid[x][y] = (int)(Math.random()*10);
}
/** 
* Creates a matrix of specified size with random values 0..9
* @param rows number of rows in matrix
* @param columns number of columns int matrix
*/
public Matrix(int rows, int columns) {
grid = new int[rows][columns];
for(int x=0; x&lt;rows; x++)
for(int y=0; y&lt;columns; y++)
grid[x][y] = (int)(Math.random()*10);
}
/**
* @return String formatted as an m x n matrix of m rows and 
* n columns
*/
public String toString() {
int rows = grid.length;
int columns = grid[0].length;
String table = new String(&quot;&quot;);
for(int x=0; x&lt;rows; x++) {
table = table + &#39;|&#39; + &#39;\t&#39;;
for(int y=0; y&lt;columns; y++)
table = table + grid[x][y] + &#39;\t&#39;;
table = table + &#39;|&#39; + &#39;\n&#39;;
}
return table;
}
/**
* @return true if number of rows equals number of columns
*/
public boolean isSquare() {
return grid.length == grid[0].length;
}
/**
* @param other another matrix to compare to this one
* @return true if this matrix and the other have the same
* number of rows and columns
*/
public boolean sameSize(Matrix other) {
return grid.length == other.grid.length &amp;&amp; 
grid[0].length == other.grid[0].length;
}
// main method: for testing
public static void main(String[] args) {
Matrix m = new Matrix();
Matrix n = new Matrix((int)(Math.random()*5)+2);
Matrix o = new Matrix(((int)(Math.random()*5)+2),
((int)(Math.random()*5)+2));
System.out.println (&quot;First matrix:&quot;);
System.out.print(m);
System.out.println (&quot;Second matrix:&quot;);
System.out.println(n);
System.out.println (&quot;Third matrix:&quot;);
System.out.println(o);
if(m.sameSize(n))
System.out.println(&quot;First two are the same size&quot;);
else
System.out.println(&quot;First two are not the same size&quot;);
if(o.isSquare())
System.out.println(&quot;All three are square matrices&quot;);
else
System.out.println(&quot;Only first two are square matrices&quot;);      
}
}

答案1

得分: 1

你首先检查矩阵的大小是否相同,然后逐个对两个矩阵中的每个值进行求和,如下所示:

public Matrix sum(Matrix other) {
    if (this.sameSize(other)) {
        Matrix result = new Matrix(this.grid.length, this.grid[0].length);
        for (int i=0; i<this.grid.length; i++) {
            for (int j=0; j<this.grid.length; j++) {
                result.grid[i][j] = this.grid[i][j] + other.grid[i][j];
            }
        }
        return result;
    } else {
        return null; // 无法对这些矩阵求和
    }
}
英文:

You first check that matrices are of the same size and then you sum up each value in both matrices one by one like

public Matrix sum(Matrix other) {
    if (this.sameSize(other)) {
        Matrix result = new Matrix(this.grid.length, this.grid[0].length);
        for (int i=0; i&lt;this.grid.length; i++) {
            for (int j=0; j&lt;this.grid.length; j++) {
                result.grid[i][j] = this.grid[i][j] + other.grid[i][j];
            }
        }
        return result;
    } else {
        return null; // Can&#39;t sum those matrices
    }
}

答案2

得分: 1

将以下内容添加到Matrix类中:

/**
 * 创建一个新的矩阵,其中包含两个矩阵的值相加的结果。
 * @param otherMatrix 要相加的矩阵。
 * @return 新的矩阵。
 */
public Matrix add(Matrix otherMatrix) {
    if (sameSize(otherMatrix)) {
        Matrix newMatrix = new Matrix(grid.length, grid[0].length);
        for (int x = 0; x < grid.length; x++) {
            for (int y = 0; y < grid[0].length; y++) {
                newMatrix.grid[x][y] = grid[x][y] + otherMatrix.grid[x][y];
            }
        }
        return newMatrix;
    } else {
        throw new Error("矩阵的大小不一致。");
    }
}

然后使用以下代码调用:

Matrix addedMatrix = matrix.add(otherMatrix);
英文:

Add this to the Matrix class:

/**
* Creates a new Matrix with the values of 
* both Matrix(s) added together.
* @param otherMatrix The Matrix to be added.
* @return The new Matrix.
*/
public Matrix add(Matrix otherMatrix) {
if (sameSize(otherMatrix)) {
Matrix newMatrix = new Matrix(grid.length, grid[0].length);
for (int x = 0; x &lt; grid.length; x++) {
for (int y = 0; y &lt; grid[0].length; y++) {
newMatrix.grid[x][y] = grid[x][y] + otherMatrix.grid[x][y];
}
}
return newMatrix;
} else {
throw new Error(&quot;The Matrix(s) aren&#39;t the same size.&quot;);
}
}

Then call it with:

Matrix addedMatrix = matrix.add(otherMatrix);

答案3

得分: 0

public class Matrix {

    private final int[][] grid;
    private final int width;
    private final int height;

    public Matrix() {
        this(3);
    }

    public Matrix(int size) {
        this(size, size);
    }

    public Matrix(int rows, int cols) {
        grid = createGrid(rows, cols);
        width = cols;
        height = rows;
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder();
        buf.append('[');

        for (int row = 0; row < grid.length; row++) {
            if (buf.length() > 1)
                buf.append(',');

            buf.append('[');

            for (int col = 0; col < grid[row].length; col++) {
                if (col > 0)
                    buf.append(',');
                buf.append(grid[row][col]);
            }

            buf.append(']');
        }

        return buf.append(']').toString();
    }

    public boolean isSquare() {
        return width == height;
    }

    public boolean isSameSize(Matrix m) {
        return m != null && width == m.width && height == m.height;
    }

    public void add(Matrix m) {
        if (!isSameSize(m))
            return;

        for (int row = 0; row < grid.length; row++)
            for (int col = 0; col < grid[row].length; col++)
                grid[row][col] += m.grid[row][col];
    }

    private static int[][] createGrid(int rows, int cols) {
        Random random = new Random();
        int[][] grid = new int[rows][cols];

        for (int row = 0; row < grid.length; row++)
            for (int col = 0; col < grid[row].length; col++)
                grid[row][col] = random.nextInt(10);

        return grid;
    }

    public static void main(String... args) {
        Random random = new Random();
        Matrix m = new Matrix();
        Matrix n = new Matrix(random.nextInt(7));
        Matrix o = new Matrix(random.nextInt(7), random.nextInt(7));
        System.out.println("第一个矩阵:");
        System.out.print(m);
        System.out.println("第二个矩阵:");
        System.out.println(n);
        System.out.println("第三个矩阵:");
        System.out.println(o);

        if (m.isSameSize(n))
            System.out.println("前两个矩阵大小相同");
        else
            System.out.println("前两个矩阵大小不同");

        if (o.isSquare())
            System.out.println("三个矩阵都是方阵");
        else
            System.out.println("只有前两个矩阵是方阵");

        n.add(o);
        System.out.println(n);
    }
}
英文:
public class Matrix {
private final int[][] grid;
private final int width;
private final int height;
public Matrix() {
this(3);
}
public Matrix(int size) {
this(size, size);
}
public Matrix(int rows, int cols) {
grid = createGrid(rows, cols);
width = cols;
height = rows;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(&#39;[&#39;);
for (int row = 0; row &lt; grid.length; row++) {
if (buf.length() &gt; 1)
buf.append(&#39;,&#39;);
buf.append(&#39;[&#39;);
for (int col = 0; col &lt; grid[row].length; col++) {
if (col &gt; 0)
buf.append(&#39;,&#39;);
buf.append(grid[row][col]);
}
buf.append(&#39;]&#39;);
}
return buf.append(&#39;]&#39;).toString();
}
public boolean isSquare() {
return width == height;
}
public boolean isSameSize(Matrix m) {
return m != null &amp;&amp; width == m.width &amp;&amp; height == m.height;
}
public void add(Matrix m) {
if (!isSameSize(m))
return;
for (int row = 0; row &lt; grid.length; row++)
for (int col = 0; col &lt; grid[row].length; col++)
grid[row][col] += m.grid[row][col];
}
private static int[][] createGrid(int rows, int cols) {
Random random = new Random();
int[][] grid = new int[rows][cols];
for (int row = 0; row &lt; grid.length; row++)
for (int col = 0; col &lt; grid[row].length; col++)
grid[row][col] = random.nextInt(10);
return grid;
}
public static void main(String... args) {
Random random = new Random();
Matrix m = new Matrix();
Matrix n = new Matrix(random.nextInt(7));
Matrix o = new Matrix(random.nextInt(7), random.nextInt(7));
System.out.println(&quot;First matrix:&quot;);
System.out.print(m);
System.out.println(&quot;Second matrix:&quot;);
System.out.println(n);
System.out.println(&quot;Third matrix:&quot;);
System.out.println(o);
if (m.isSameSize(n))
System.out.println(&quot;First two are the same size&quot;);
else
System.out.println(&quot;First two are not the same size&quot;);
if (o.isSquare())
System.out.println(&quot;All three are square matrices&quot;);
else
System.out.println(&quot;Only first two are square matrices&quot;);
n.add(o);
System.out.println(n);
}
}

huangapple
  • 本文由 发表于 2020年9月22日 20:51:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64010122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定