如何根据每一行将矩阵转换为对角矩阵的堆栈? [英] How to convert matrix to a stack of diagonal matrices based on every row?

查看:135
本文介绍了如何根据每一行将矩阵转换为对角矩阵的堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵:

A = [1 1 1
     2 2 2
     3 3 3]

是否有矢量化的获取方式:

Is there a vectorized way of obtaining:

B = [1 0 0 
     0 1 0
     0 0 1
     2 0 0 
     0 2 0
     0 0 2
     3 0 0 
     0 3 0
     0 0 3]

推荐答案

这是使用 repmat :

Here's another way using sparse and repmat:

A = [1 2 3; 4 5 6; 7 8 9];
A = A.';
B = full(sparse(1:numel(A), repmat(1:size(A,1),1,size(A,2)), A(:)));

原始矩阵位于A中,我对其进行了转置,因此可以为下一步骤正确展开每个矩阵的行.我使用sparse声明矩阵中的非零值.具体来说,我们看到每行只有一个条目,因此行索引的范围应从1到与A中的条目数量一样多.列从1到最后一列波动并重复. mod当然是通过waywaywalk解决方案的方法,但是我想使用repmat,因此这是与他的方法无关的解决方案.这样,我们创建了一个向量来访问从1到我们所拥有的所有列的列,并针对我们所拥有的尽可能多的行重复此操作.这些行和列索引向量将指示非零位置的显示位置.最后,按照行和列索引向量所指定的顺序,将以行主要顺序展开的A元素会进入每个非零位置.

The original matrix is in A, and I transpose it so I can unroll the rows of each matrix properly for the next step. I use sparse to declare what is non-zero in a matrix. Specifically, we see that there is only one entry per row and so the row indices should range from 1 up to as many entries as there are in A. The columns fluctuate from 1 up to the last column and repeat. mod is certainly the way to go via thewaywewalk's solution, but I wanted to use repmat so that this is an independent solution from his approach. As such, we create a vector for accessing the columns that goes from 1 up to as many columns as we have, and we repeat this for as many rows as we have. These row and column index vectors are is going to dictate where the non-zero locations will appear. Finally, what will go into each non-zero location are the elements of A unrolled in row major order, following the order dictated by the row and column index vectors.

请注意,在repmat调用中,由于转置操作,调用size时的行和列将颠倒.

Take note that in the repmat call, the rows and columns when calling size are reversed due to the transpose operation.

结果如下,我们得到:

>> B

B =

     1     0     0
     0     2     0
     0     0     3
     4     0     0
     0     5     0
     0     0     6
     7     0     0
     0     8     0
     0     0     9

鉴于上述问题的稀疏性,将矩阵保留为sparse形式并在必要时仅使用full进行转换可能会更快.将会花费时间在两种格式之间进行转换,因此,如果您决定进行基准测试,请考虑到这一点.

Given the sparsity of the above problem, it may be faster to leave the matrix in sparse form and only convert using full if necessary. There will be time spent to convert between the two formats so take that into consideration if you decide to benchmark.

这篇关于如何根据每一行将矩阵转换为对角矩阵的堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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