创建对角矩阵(高维) [英] Creating a diagonal matrix (higher dimension)

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

问题描述

我有一个n * m矩阵,例如A.我想创建以下m * m * n矩阵,例如B

I have an n* m matrix, say A. I'd like to create the following m* m*n matrix, say B

for j=1:n
    B(:,:,j)=diag(A(j,:));
end

如何做到这一点而无需循环?

How do I do this without having to loop?

谢谢

推荐答案

更新:我已经编辑了问题,以修复示例代码中的错字.

UPDATE: I've edited the question to fix the typos in the sample code.

我非常确定您的示例代码包含一些错字,因为当前矩阵A没有任何作用,循环下标j也没有作用.但是,您似乎实际上想问的似乎是:我如何构建一个3d数组,其中每个对角线(沿第3维移动)是A中的一行,而不进行循环?

I'm fairly sure your example code contains a couple of typos, since currently the matrix A serves no purpose, nor does your looping subscript j. However, it seems reasonably likely that what you actually are trying to ask is: How do I build a 3d array where each diagonal (moving along the 3rd dimension) is a row from A, without doing a loop?

如果正确,那么答案如下:

If this is correct, then one answer is as follows:

%# A loop-less solution
Soln2 = zeros(M, M, N);
Soln2(bsxfun(@plus, (1:M+1:M*M)', (0:M^2:(N-1)*M^2))) = A';

基本上,我所做的全部工作是预先分配解决方案3d数组,然后使用bsxfun构造所有对角线的线性索引,沿第3维移动.然后,我将A的转置(因为您想要行而不是列)分配给解决方案数组中的线性索引.

Essentially all I've done is pre-allocate the solution 3d array, and then used bsxfun to construct a linear index of all the diagonals, moving along the 3rd dimension. I then assign the transpose of A (because you want rows not columns) to the linear index in the solution array.

注意,我在下面粘贴了一些示例代码以进行测试.请验证我对您基于循环的解决方案的理解是您真正追求的.

Note, I've pasted some sample code for testing purposes below. Please verify that my interpretation of your loop-based solution is what you are really after.

%# Set some parameters and create a random matrix A
N = 3;
M = 4;
A = randi(5, N, M);

%# Your loop based solution
Soln1 = nan(M, M, N);
for n = 1:N
    Soln1(:,:,n) = diag(A(n,:));
end

%# A loop-less solution
Soln2 = zeros(M, M, N);
Soln2(bsxfun(@plus, (1:M+1:M*M)', (0:M^2:(N-1)*M^2))) = A';

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

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