Sample Entropy Wikipedia includes the MATLAB version of the code. However, when I run it on my dataset, I get NaN for my result.
Convert Python Code to MATLAB Code?
3 views (last 30 days)
Show older comments
How can I convert Python code to MATLAB code? I want to convert the approximate entropy Python implementation on wikipedia to MATLAB:
Approximate Entropy:
import numpy as np
def ApEn(U, m, r):
def _maxdist(x_i, x_j):
return max([abs(ua - va) for ua, va in zip(x_i, x_j)])
def _phi(m):
x = [[U[j] for j in range(i, i + m - 1 + 1)] for i in range(N - m + 1)]
C = [len([1 for x_j in x if _maxdist(x_i, x_j) <= r]) / (N - m + 1.0) for x_i in x]
return (N - m + 1.0)**(-1) * sum(np.log(C))
N = len(U)
return abs(_phi(m+1) - _phi(m))
I would like to run the code without having to install Python, so I would like to convert the algorithm into MATLAB language. Thank you!
Answers (1)
Aymane Amouri
on 5 May 2021
"
import numpy as np
from lmfit import Minimizer, Parameters, report_fit
# create data to be fitted
x = np.linspace (0, 15, 301)
data = (10. * np.sin (2 * x - 0.1) * np.exp (-x * x * 0.025) +
np.random.normal (size=len (x), scale=0.2))
# define objective function: returns the array to be minimized
def fcn2min(params, x, data):
""" model decaying sine wave, subtract data"""
amp = params['amp']
shift = params['shift']
omega = params['omega']
decay = params['decay']
model = amp * np.sin (x * omega + shift) * np.exp (-x * x * decay)
return model - data
# create a set of Parameters
params = Parameters ( )
params.add ('amp', value=1, min=0)
params.add ('decay', value=0.1)
params.add ('shift', value=0.0, min=-np.pi / 2., max=np.pi / 2)
params.add ('omega', value=3.0)
# do fit, here with leastsq model
minner = Minimizer (fcn2min, params, fcn_args=(x, data))
kws = {'options': {'maxiter': 10}}
result = minner.minimize ( )
# calculate final result
final = data + result.residual
# write error report
report_fit (result)
# try to plot results
try:
import pylab
pylab.plot (x, data, 'k+')
pylab.plot (x, final, 'r')
pylab.show ( )
except:
pass
pylab.plt.figure( )
"
j'ai besoin de transformer ce code python to matlab code
1 Comment
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!