Writing a summation code where i≠j
2 次查看(过去 30 天)
显示 更早的评论
.
Here, x is a 1xn vector, and w is a square matrix where w_ii=0
I wrote the code to calculate the denominator, but it's quite complicated to calculate the nominator.
I tried with the below code, but I'm not sure it's right...
How can I do that?
x = [1,2,3,4]; % feature vector
w= rand(4,2); D=pdist(w);
W= squareform(D); % weight matrix
% Calculate Denominator
denom=0;
for i = 1:4
for j = 1:4
if i~=j
denom = denom + x(j)*x(i);
end
end
end
% Calculate nominator
Wu = triu(W,1);
Wd = tril(W,-1);
nom = (sum(sum(Wu)) + sum(sum(Wd))) * denom;
0 个评论
采纳的回答
Voss
2022-6-10
The weight matrix is zeros along the diagonal. Thus you can use it as-is in the summation, since the terms where i==j (which correspond to the diagonal elements of W) will be 0.
To get the same effect in the denominator, you can set the diagonal elements of x.*x.' to zero and use that.
x = [1,2,3,4]; % feature vector
w = rand(4,2);
D = pdist(w);
W = squareform(D) % weight matrix
denom_matrix = x.*x.';
denom_matrix(1:numel(x)+1:end) = 0
G = sum(W.*x.*x.','all')/sum(denom_matrix,'all')
For reference, here is a way to do the same thing using for loops:
denominator = 0;
numerator = 0;
for ii = 1:numel(x)
for jj = 1:numel(x)
if ii == jj % skip the ii == jj terms
continue
end
denominator = denominator + x(ii)*x(jj);
numerator = numerator + W(ii,jj)*x(ii)*x(jj);
end
end
G_loop = numerator/denominator
Check that the results are identical:
isequal(G,G_loop)
更多回答(2 个)
Abhishek Chakram
2022-6-10
Hi,
You can do it the same way as you calculated the denominator. The code will look like :
numerator = 0;
for i = 1:4
for j = 1:4
if i~=j
numerator = numerator + W(i,j)*x(i)*x(j);
end
end
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!