![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/621888/image.png)
convert code from a python function to matlab
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/621853/image.png)
0 commentaires
Réponse acceptée
Walter Roberson
le 18 Mai 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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/621888/image.png)
0 commentaires
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Data Type Conversion dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!