从折叠的3D矩阵中找到对角线

时间:2014-06-24 15:36:26

标签: matlab matrix vectorization diagonal

我有一个3D矢量v

A = rand(2, 2, 2);
v = sum(A, 2);

现在我只是做了:

B = diag(v);
Error using diag
First input must be 2D. 

使用循环,我执行了以下操作:

for i = 1:2
   B{i} = diag(v(:, :, i));
end

我想从我的3D矢量中获取3D矩阵。假设我有以下向量:

v(:, :, 1)=[1 2 3]';
v(:, :, 2)=[1 2 4]';
%I would like to get, using some command and without loop (if possible), a 3D matrix B
B(:, :, 1)=[1 0 0; 
            0 2 0; 
            0 0 3];
B(:, :, 2)=[1 0 0;
            0 2 0;  
            0 0 4];

2 个答案:

答案 0 :(得分:2)

我只是从问题的最后几行开始假设您有v并且您希望B没有循环。同样,我认为这对你有用 -

%// Input
v(:, :, 1)=[1 2 3]';
v(:, :, 2)=[1 2 4]';

[M,~,P] = size(v)
B = zeros(size(v,1),size(v,1),size(v,3));
B(bsxfun(@plus,[1:M+1:M*M]',[0:P-1]*M*M)) = v %//'

输出 -

B(:,:,1) =
     1     0     0
     0     2     0
     0     0     3
B(:,:,2) =
     1     0     0
     0     2     0
     0     0     4

答案 1 :(得分:2)

另一种可能性:

result = arrayfun(@(k) diag(v(:,:,k)), 1:size(v,3), 'UniformOutput', false);
result = cat(3, result{:});

或者,如果您想要一行,请使用cell2matreshape代替cat

result = reshape(cell2mat(arrayfun(@(k) diag(v(:,:,k)), 1:size(v,3), 'UniformOutput', false)), size(v,1), size(v,1), size(v,3));