如何向量化矩阵的逐行对角化 [英] How to vectorize row-wise diagonalization of a matrix

查看:85
本文介绍了如何向量化矩阵的逐行对角化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个n×m矩阵,我想将其转换为mn×m矩阵,结果的每个m×m块都包含每一行的对角线.

I have an n-by-m matrix that I want to convert to a mn-by-m matrix, with each m-by-m block of the result containing the diagonal of each row.

例如,如果输入为:

[1 2; 3 4; 5 6]

输出应为:

[1 0; 0 2; 3 0; 0 4; 5 0; 0 6]

当然,我不想自己用for循环逐步组装矩阵.
有矢量化的简单方法可以实现这一目标吗?

Of course, I don't want to assemble the matrix step by step myself with a for loop.
Is there a vectorized and simple way to achieve this?

推荐答案

使用矢量化方法,将对角线元素的线性索引创建到结果矩阵中,然后直接赋值.

For a vectorized way to do this, create the linear indices of the diagonal elements into the resulting matrix, and assign directly.

%# create some input data
inArray = [10 11;12 13;14 15];

%# make the index array
[nr,nc]=size(inArray);

idxArray = reshape(1:nr*nc,nc,nr)';
idxArray = bsxfun(@plus,idxArray,0:nr*nc:nr*nc^2-1);

%# create output
out = zeros(nr*nc,nc);
out(idxArray) = inArray(:);

out =

    10     0
     0    11
    12     0
     0    13
    14     0
     0    15

这篇关于如何向量化矩阵的逐行对角化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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