如何从向量的java向量(多维向量)创建矩阵 [英] How to create matrix from java vector of vectors (Multidimentional Vector)

查看:77
本文介绍了如何从向量的java向量(多维向量)创建矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试像多维数组一样在 java 中创建 Vectors(2d) 的向量.然后将值分配给该矩阵中的特定位置,就像我们在二维数组中使用 matrix[i][j] 所做的那样任何帮助.

am trying to create vector of Vectors(2d) in java like multidimensional array. then to assign values to specific position in that matrix like what we do using matrix[i][j] in 2D array Any help.

我的数据在一个向量中:

My data in one Vector:

n = [a, b, c, d, e, f, g , h]

我想创建 2D Vector 来表示向量 m =

I want to create 2D Vector to represent vector m =

  • a b c d
  • e f g h

推荐答案

无论出于何种原因,SO 遇到了您的问题就在几分钟前.到 2021 年,您可能不会再使用 Vector,而是使用 List.实际上他们都有 subList(start,end) 方法(即使在 Java 7 中链接指向的内容也是如此),因此实际上您只需按行大小循环遍历向量/列表并使用此方法.
此外,您可能喜欢使用流,因此流收集器会为您完成此操作,而不是在单独的行中初始化结果变量:

For whatever reasons, SO bumped your question just a couple minutes ago. In 2021 you probably would not use Vector any more, but List. Actually both of them have subList(start,end) method (even in Java 7 what the link points to), so practically you would just loop over vector/list in row-sized steps and use this method.
Also, you might fancy using streams so instead of initializing the result variable in a separate line, the stream collector does that for you:

List<Integer> vector=Arrays.asList(1,2,3,4,5,6,7,8);
int rowSize=4;
List<List<Integer>> matrix=IntStream.range(0, vector.size()/rowSize)
        .mapToObj(row->vector.subList(row*rowSize, (row+1)*rowSize))
        .collect(Collectors.toList());
System.out.println(matrix);

将输出[[1, 2, 3, 4], [5, 6, 7, 8]].

此外,由于 Vector 可以从 List 构造,毕竟你也可以这样做:

Also, as Vector can be constructed from List, after all you can do that too:

Vector<Integer> vector=new Vector<Integer>(Arrays.asList(1,2,3,4,5,6,7,8));
int rowSize=4;
Vector<Vector<Integer>> matrix=new Vector<Vector<Integer>>(
        IntStream.range(0, vector.size()/rowSize)
        .mapToObj(row->new Vector<Integer>(vector.subList(row*rowSize, (row+1)*rowSize)))
        .collect(Collectors.toList()));
System.out.println(matrix);

当然,在后台,它们的作用与 for 循环几乎相同:

And of course in the background both of them do pretty much the same as a for loop would have done:

Vector<Integer> vector=new Vector<Integer>(Arrays.asList(1,2,3,4,5,6,7,8));
int rowSize=4;
Vector<Vector<Integer>> matrix=new Vector<Vector<Integer>>();
for(int row=0;row<vector.size()/rowSize;row++)
    matrix.add(new Vector<Integer>(vector.subList(row*rowSize, (row+1)*rowSize)));
System.out.println(matrix);

这篇关于如何从向量的java向量(多维向量)创建矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆