0

I have a couple of vectors that I want to summarize to matrix array.

   vector1 = {1, 2, 3, 4, 5}
   vector2 = {1, 4, 3, 6, 5}
   vector3 = {8, 2, 3, 4, 5}

   matrix [][] ={{1, 2, 3, 4, 5},
                 {1, 4, 3, 6, 5},
                 {8, 2, 3, 4, 5}};

How can I easily create such a matrix?

3
  • Which programming language is this? Commented Dec 17, 2014 at 15:23
  • @codor: oh I'm sorry. I need it for java Commented Dec 17, 2014 at 15:24
  • The question is a duplicate of stackoverflow.com/questions/4781100/… Commented Dec 17, 2014 at 15:24

3 Answers 3

1

I don't know what type your Vectors are, but I'll assume they're Integers for now. Replace Integer with whatever type you're using if you aren't.

If you're willing to use a Vector instead of an array, you can declare matrix like:

Vector<Vector<Integer>> matrix = new Vector<Vector<Integer>>();

And you can then add the elements like

matrix.add(vector1);
matrix.add(vector2);
matrix.add(vector3);

You'll then be able to access elements like

matrix.get(2).get(4); //Returns 6 from the sample data

If you really want to use arrays, for whatever reason, it's still not hard to do, it's just another method from your vectors.

You would instead declare your matrix like:

Integer[][] matrix = {vector1.toArray(), vector2.toArray(), vector3.toArray()};

Then you can access elements like

matrix[2][4]; //Returns 6 from the sample data

I will note, I'm not 100% that you'd need to do Integer[][] instead of just int[][], but I think since you can't use primitives for your Vector's generic you might have to keep on using Integer.

Sign up to request clarification or add additional context in comments.

Comments

0
    Integer[][] matrix = new Integer[3][5];
    **static**
        matrix[0][0] == 1;
        matrix[0][1] == 2;
        matrix[0][2] == 3;
        matrix[0][3] == 4;
        matrix[0][4] == 5;    
        matrix[1][0] == 1;
        matrix[1][0] == 4;
        matrix[1][0] == 3;
        matrix[1][0] == 6;
        matrix[1][0] == 5;
        matrix[1][0] == 8;
        matrix[1][0] == 2;
        matrix[1][0] == 3;
        matrix[1][0] == 4;
   **dynamic**
        Integer[][] matrix = {vector1.toArray(), vector2.toArray(), vector3.toArray()};

Comments

0

It seems that your program will use matrix in multiple places, and after a while you will have to reinvent the wheel and write part of your own library for matrices.

You should seriously consider using some already existing library for them.

With current approach half of your code will consist of for loops which operate on 2D (or more) arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.