我想生成一个矩阵,其中i,j元素等于i * j,其中i!= j。

例如

0 2 3
2 0 6
3 6 0

到目前为止,我已经知道可以使用此索引矩阵访问非对角元素
idx = 1 - eye(3)

但我还没有弄清楚如何将矩阵单元的索引合并到计算中。

最佳答案

我正在考虑一般情况(矩阵不一定是正方形)。让

m = 4; %// number of rows
n = 3; %// number of columns

有很多方法:
  • 使用ndgrid:
    [ii jj] = ndgrid(1:m,1:n);
    result = (ii.*jj).*(ii~=jj);
    
  • 使用bsxfun:
    result = bsxfun(@times, (1:m).',1:n) .* bsxfun(@ne, (1:m).',1:n);
    
  • 使用repmatcumsum:
    result = cumsum(repmat(1:n,m,1));
    result(1:m+1:m^2) = 0;
    
  • 使用矩阵乘法(由@GastónBengolea添加):
    result = (1:m).'*(1:n).*~eye(m,n);
    
  • 关于arrays - 在矩阵中将矩阵中的元素i,j设置为i * j,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22237082/

    10-11 23:06
    查看更多