【发布时间】:2014-03-06 22:06:41
【问题描述】:
我想生成一个矩阵,其中 i,j 元素等于 i*j,其中 i != j。
例如
0 2 3
2 0 6
3 6 0
到目前为止,我发现我可以使用这个索引矩阵访问非对角元素
idx = 1 - eye(3)
但我还没有弄清楚如何将矩阵单元的索引合并到计算中。
【问题讨论】:
我想生成一个矩阵,其中 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);
使用repmat 和cumsum:
result = cumsum(repmat(1:n,m,1));
result(1:m+1:m^2) = 0;
使用矩阵乘法(由@GastónBengolea 添加):
result = (1:m).'*(1:n).*~eye(m,n);
【讨论】:
怎么样
N=3; %size of matrix
A=[1:N]'*[1:N]-diag([1:N].^2)
【讨论】:
[1:N]'*[1:N].*~diag([1:N])
还有一个技巧是滥用kron函数:
>> m = 4;
>> n = 3;
>> a = kron((1:m)', 1:n);
>> a(eye(m, n, 'logical')) = 0
a =
0 2 3
2 0 6
3 6 0
4 8 12
【讨论】:
kron。嘿,为什么a(1:m+1:end) = 0 傻? ;-) 无论如何,如果 n>m 可能不起作用(但我不认为这就是你这么说的原因)。你需要a(1:m+1:min(m,n)^2)=0
m^2 就足够了。我已经更新了答案
for i=1:3
for j=1:3
if i==j
A(i,j)=0;
else
A(i,j)=i*j;
end
end
end
【讨论】:
A=zeros(3); 以使代码更快(然后您可以删除if 的第一个分支)。另外,for 循环在 Matlab 中是 may not be the best choice
A[i j] 什么都不是。我猜你的意思是A[i,j]),所以答案并不是一个完整的答案。
bsxfun 和 ndgrid