Reputation: 672
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?
Upvotes: 0
Views: 331
Reputation: 11433
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.
Upvotes: 0
Reputation: 4076
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()};
Upvotes: 0
Reputation: 322
I don't know what type your Vectors are, but I'll assume they're Integer
s 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
.
Upvotes: 1