MATLAB: Fresnel functions, with vectors

fresnel

function y = fresnelS(f,x,n)
if mod(n,2) == 1
error('The number of strips must be even!');
end
h = x/n;
y = f(x);
for k = 1:2:n
y = y + 4*f(k*h);
end
for k=2:2:n-1
y = y + 2*f(k*h);
end
y = y*h/3;
How would you modfiy this code so that x can be a vector, e.g. fresnelS(@(x) sin(x^2), [3 2 1], n)

Best Answer

You only need to make one ‘hard’ modification to vectorise your function, that being the last line. Otherwise, use the vectorize (link) function, with the str2func (link) function to allow your function to be compatible with vector inputs:
function y = fresnelS(f,x,n)
f = str2func(vectorize(f))
if mod(n,2) == 1
error('The number of strips must be even!');
end
h = x/n;
y = f(x);
for k = 1:2:n
y = y + 4*f(k*h);
end
for k=2:2:n-1
y = y + 2*f(k*h);
end
y = y.*h/3;
end
Calling it as:
n = 42;
y1 = fresnelS(@(x) sin(x^2), [3 2 1], n)
produces:
y1 =
0.773589281078057 0.80477821467003 0.310268275967617
Success!
Related Question