用对角矩阵替换矩阵中的每个元素

时间:2015-03-20 22:15:22

标签: matlab matrix vectorization

假设我有一个尺寸为NxV的矩阵A.我想创建一个更大的矩阵大小为NTxVT,即我想用diag(T)* A(e)替换矩阵A(e)的每个元素e,同时保持矩阵的一般方向(例如, A(e)在A(e-1)的左边,因此diag(T)* A(e)在diag(T)* A(e-1)的左边。

在matlab中有一个技巧可以实现吗? (制作每个对角矩阵并将它们连接起来将永远存在)。

非常感谢^^

5 个答案:

答案 0 :(得分:6)

A = magic(3);
T = diag([-1 1]);
kron(A,T)

给出

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

PS。我从this example

复制了这个想法

答案 1 :(得分:4)

以下是使用bsxfun

的解决方案
A = magic(3);
T = [-1 1]
T = diag(T);
M=bsxfun(@times,permute(A,[3,1,4,2]),permute(T,[1,3,2,4]));
M=reshape(M,size(T).*size(A));

它会创建一个4D-Matrix,其中各个块为M(:,i,:,j),然后将其重新整形为2D-Matrix。

图像处理工具箱提供了另一种非常短但很慢的解决方案:

A = magic(3);
T = [-1 1]
T = diag(T);
M=blockproc(A,[1 1],@(x) x.data.*T);

最后一个生成稀疏矩阵的实现,可能对大T有用,因为你的矩阵将包含很多零:

T=[-1 1];
A=magic(3);
%p and q hold the positions where the first element element is stored. Check sparse(p(:),q(:),A(:)) to understand this intermediate step
[p,q]=ndgrid(1:numel(T):numel(T)*size(A,1),1:numel(T):numel(T)*size(A,2));
%now p and q are extended to hold the indices for all elements
tP=bsxfun(@plus,p(:),0:numel(T)-1);
tQ=bsxfun(@plus,q(:),0:numel(T)-1);
%
tA=bsxfun(@times,A(:),T);
M=sparse(tP,tQ,tA);

当T的大小为nx1时,稀疏解决方案会将内存使用量减少大约n / 1.55。

答案 2 :(得分:3)

我能想到的最简单的方法是合并arrayfuncell2mat函数:

B = cell2mat(arrayfun((@(x) T .* x), A, 'UniformOutput', false));

首先,我将矩阵A转换为矩阵T .* x的单元格数组,其中xA的元素(假设T是一个矩阵)。

然后我使用cell2mat转换回矩阵。

这是一个完整的示例(execute online):

A = magic(3);
T = diag([-1 1]);
B = cell2mat(arrayfun((@(x) T .* x), A, 'UniformOutput', false));

导致:

B =

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

答案 3 :(得分:1)

仅使用索引:

A = magic(3); 
T = diag([-1 1]); %// example data from Daniel's answer
[a1, a2] = size(A);
[t1, t2] = size(T);
M = A(ceil(1/t1:1/t1:a1), ceil(1/t2:1/t2:a2)).*T(repmat(1:t1,1,a1), repmat(1:t2,1,a2));

答案 4 :(得分:1)

使用good old-fashioned matrix multiplication -

M = reshape(diag(T)*A(:).',[size(A,1)*size(T,1) size(A,2)])

示例运行 -

A = magic(4)
T = magic(3)
M = reshape(diag(T)*A(:).',[size(A,1)*size(T,1) size(A,2)])

将导致 -

A =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1
T =  %// Notice that only diag(T) elements would be used to calculate M 
     8     1     6
     3     5     7
     4     9     2
M =
   128    16    24   104
    80    10    15    65
    32     4     6    26
    40    88    80    64
    25    55    50    40
    10    22    20    16
    72    56    48    96
    45    35    30    60
    18    14    12    24
    32   112   120     8
    20    70    75     5
     8    28    30     2
相关问题