Hello! I'm trying to transform working Python code to Matlab code. It's Simpson's rule. But MatLab code is not working. What should I change for in this code?

Python:

``````from math import sin

def f(x):
return ((0.6369)*sin(sin(x))*sin(x))

def method_simpson_compost(f,a,b,n):

h  = (float(b)-a)/n
i   = 0
fks = 0.0
while i<=n:
xk = a+i*h
if i==0 or i==n:
fk = f(xk)
elif i%2 == 1:
fk = 4*f(xk)
else:
fk = 2*f(xk)
fks += fk
i += 1
return (h/3)*fks
print method_simpson_compost(f, 0, 1.57, 10)
``````

MatLab code:

file-function "f.m":

``````function func = f(z, x)
f = ((0.6369).*sin(z.*sin(x)).*sin(x))
``````

file-function "s.m":

``````function simpson = s(f, a, b, n)
h  = (b-a)/n;
i   = 0;
fks = 0.0;
while (i<=n)
xk = a+i*h;
if i==or(0, n)
fk = f(z,xk);
if rem(5, 2) == 1
fk = 4.*f(z,xk);
else
fk = 2.*f(z,xk);
fks = fks + fk;
i = i + 1;
end
simpson = (h./3).*fks;
``````

Thanks in advance.

Recommended Answers

I have a running version for scilab here. I didn't check that the numerical result is good however

``````clear;
function func = foo(z, x)
func = ((0.6369).*sin(z.*sin(x)).*sin(x))
endfunction

function simpson = simpson(f, a, b, n)
h  = (b-a)/n;
i   = 0;
fks = 0.0;
while (i<=n)
xk = a+i*h;
if …``````

All 3 Replies

I have a running version for scilab here. I didn't check that the numerical result is good however

``````clear;
function func = foo(z, x)
func = ((0.6369).*sin(z.*sin(x)).*sin(x))
endfunction

function simpson = simpson(f, a, b, n)
h  = (b-a)/n;
i   = 0;
fks = 0.0;
while (i<=n)
xk = a+i*h;
if i==or(0, n) then
fk = f(xk);
elseif (i-fix(i./2).*2)== 1 then
// https://help.scilab.org/docs/5.5.0/en_US/m2sci_rem.html
fk = 4.*f(xk);
else
fk = 2.*f(xk);
end
fks = fks + fk;
i = i + 1;
end
simpson = (h./3).*fks;
endfunction

function func = baz(x)
func = foo(1, x)
endfunction

simpson(baz, 0, 1.57, 10)
``````

Thanks a lot, Gribouillis. But if anyone know how to do it using MatLab file-functions?