将向量转换为矩阵

时间:2016-03-05 09:48:21

标签: java

首先,这是我的代码

Matrix class;

public class Matrix {
double[][] myArray = new double[4][4];

public Matrix(double myArray[][]){
    this.myArray=myArray;
   }
}

package p1;

public class Vector {
      double []yourArray;
public Vector(double... yourArray) {
        this.yourArray = yourArray;
      }
    }

public class Test {

public static void main(String[] args) {
    Vector myVector = new Vector(1.0,2.0,3.0,4.0);

    double[] myArray = {1.0, 2.0, 3.0, 4.0};
    Vector myVector2 = new Vector(myArray);
    }
}

我有一些指示要做;

构造函数:编写三个构造函数

(1)采用二维数组并将其设置为矩阵。

(2)将矢量列表作为逗号分隔的参数列表,并将这些矢量从第一个到最后一个转换为矩阵(Vector是下面将要解释的另一个类),并从这些矢量构造矩阵或创建它们作为由另一个参数确定的矩阵的列或原始。(如果0将它们视为原始向量,如果1将这些向量视为矩阵的列)

(3)取一个整数并产生由该整数确定的维度的单位矩阵。

我做了第一个,但在第二个,我无法从vector类转移代码

2 个答案:

答案 0 :(得分:0)

试试这个。

    public Matrix(Vector... vectors) {
        myArray = new double[vectors.length][];
        for (int i = 0; i < vectors.length; ++i) {
            double[] a = vectors[i].yourArray;
            myArray[i] = Arrays.copyOf(a, a.length);
        }
    }

答案 1 :(得分:0)

使用嵌套for循环。

public class Vector{
    private double array[];
    public Vector(double array[]){
        this.array = array;
    }
    public int length(){
        return this.array.length;
    }
    public double get(int i){
        return array[i];
    }
}


public class Matrix{
    private double matrix[][];
    public Matrix(int length){
        this.matrix = new double[length][length];
        for(int i=0; i<length; i++){
            for(int j=0; j<length; j++){
                if(i==j)
                    this.matrix[i][j] = 1;
                else
                    this.matrix[i][j] = 0;
            }   
        }
    }
    public Matrix(int type,Vector...vectors){
        if(type == 1)
            this.matrix = new double[vectors.length][vectors[0].length()];
        else
            this.matrix = new double[vectors[0].length()][vectors.length];

        for(int i=0; i<vectors.length; i++){
            for(int j=0; j<vectors[i].length(); j++){
                if(type == 1)
                    this.matrix[i][j] = vectors[i].get(j);
                else
                    this.matrix[j][i] = vectors[i].get(j);
            }
        }
    }
    public double get(int i, int j){
        return matrix[i][j];
    }
}