给定 C++ 中的列,变换右上三角矩阵
我有一个包含类似内容的向量
{1, 2, 1, 4, 5, 1, 7, 8 ,9, 1 }
因此该向量表示右上矩阵的列
1 2 4 7
0 1 5 8
0 0 1 9
0 0 0 1
我如何使用该向量并从
{1, 2, 1, 4, 5, 1, 7, 8 ,9, 1 }
to
1 2 4 7
2 1 5 8
4 5 1 9
7 8 9 1
作为向量
{ 1,2,4,7,
2,1,5,8,
4,5,1,9,
7,8,9,1 }
事实上在查看代码后,解决方案是:
for (int i = 0; i < cols; ++i)
for (int j = 0; j <= i; ++j)
v[cols * i + j] = v[cols * j + i] = w[k++];
I have a vector containing something like
{1, 2, 1, 4, 5, 1, 7, 8 ,9, 1 }
So the vector represent the columns of an upper right matrix
1 2 4 7
0 1 5 8
0 0 1 9
0 0 0 1
How could I use the vector and get from
{1, 2, 1, 4, 5, 1, 7, 8 ,9, 1 }
to
1 2 4 7
2 1 5 8
4 5 1 9
7 8 9 1
as a vector
{ 1,2,4,7,
2,1,5,8,
4,5,1,9,
7,8,9,1 }
In fact After reviewing the code, the solution is:
for (int i = 0; i < cols; ++i)
for (int j = 0; j <= i; ++j)
v[cols * i + j] = v[cols * j + i] = w[k++];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设源向量为 w,dest 为 v。
如果它应该是 1D,而不是 2D,则应将
[i][j]
更改为[4*i+j]
。编辑
这可以“就地”完成,但有点棘手。为了不覆盖尚未使用的值,您必须向后循环并进行两次传递:
Assuming source vector is w, dest is v.
If it should be 1D, not 2D, then
[i][j]
should be changed to[4*i+j]
.EDIT
This can be done 'in-place', but it is a little tricky. In order not to overwrite values you haven't used yet, you have to loop backwards and to make two passes: