更改矩阵数组的对角线

时间:2017-08-10 16:14:11

标签: arrays matlab multidimensional-array octave

我有一个带有矩阵数组的应用程序。我必须多次操纵对角线。其他元素没有变化。我想做的事情如下:

for j=1:nj
  for i=1:n
      g(i,i,j) = gd(i,j)
   end
 end

我已经看到如何使用逻辑(eye(n))作为单个索引的单个矩阵来执行此操作,但这不适用于矩阵数组。当然有办法解决这个问题。感谢

2 个答案:

答案 0 :(得分:4)

使用linear index,如下所示:

g = rand(3,3,2); % example data
gd = [1 4; 2 5; 3 6]; % example data. Each column will go to a diagonal
s = size(g); % size of g
ind = bsxfun(@plus, 1:s(1)+1:s(1)*s(2), (0:s(3)-1).'*s(1)*s(2)); % linear index
g(ind) = gd.'; % write values

结果:

>> g
g(:,:,1) =
   1.000000000000000   0.483437118939645   0.814179952862505
   0.154841697368116   2.000000000000000   0.989922194103104
   0.195709075365218   0.356349047562417   3.000000000000000
g(:,:,2) =
   4.000000000000000   0.585604389346560   0.279862618046844
   0.802492555607293   5.000000000000000   0.610960767605581
   0.272602365429990   0.551583664885735   6.000000000000000

答案 1 :(得分:0)

根据Luis Mendo的回答,根据某个人的具体目的,可能更容易修改的版本。毫无疑问,他的版本在计算上会更有效率。

g = rand(3,3,2); % example data
gd = [1 4; 2 5; 3 6]; % example data. Each column will go to a diagonal
sz = size(g); % Get size of data
sub = find(eye(sz(1))); % Find indices for 2d matrix

% Add number depending on location in third dimension.
sub = repmat(sub,sz(3),1); %  
dim3 = repmat(0:sz(1)^2:prod(sz)-1, sz(1),1); 
idx = sub + dim3(:);

% Replace elements.
g(idx) = gd;
相关问题