convert code from a python function to matlab
1 view (last 30 days)
Show older comments
How to convert the following python code to matlab code?
below I send the code.
Thank you so much
# lambda L;
def J(X):
L=0.5
Xorigin=np.zeros([2,1])
JA=np.mean(np.sum(np.power(X-np.tile(Xorigin,(1,P)),2),axis=0))
JB=0
for i in range(0,P):
for j in range(i+1,P):
JB+=1/np.sum(np.power(X[:,i]-X[:,j],2))
JB=JB/(P*(P-1)/2)
return JA+L*JB
Function:
0 Comments
Accepted Answer
Walter Roberson
on 18 May 2021
X = randi([-9 9], 10, 2)
disp(J(X))
function output = J(X)
L = 0.5;
S = size(X,1);
JA = sum(X.^2,2);
JB = sum(triu(squareform(1./pdist(X, 'squaredeuclidean'))),2);
output = sum(JA + JB)./S;
end
The equation you posted does not include a division by P*(P-1)/2 (for undefined variable P at that.)
The equation you posted is ambiguous about what the upper limit is for j. As s is not defined, it is possible that the size of X is greater than s, so the sum in the second part of the equation might include a potentially large number of terms.
The posted equation has j>=i but when j = i then is 0 and the term would be 1/0 which is infinity. That is not a useful equation, so we must suppose that j>i must be true. If s is the number of rows in X then for the last row, i = s, j>i would be empty, which leads to the question of whether adding emptiness should be treated the same as adding 0.
0 Comments
More Answers (1)
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!