Replacing for loop in the function

5 views (last 30 days)
Haider Ali on 8 Sep 2021
Commented: Star Strider on 8 Sep 2021
Can someone please help me to remove this for loop in the function below and still get the same result that I get with loops?
function I = func(f, a, b, n)
% Add description, name, date, inputs, outputs
h = (b-a)/n;
I = 0;
for j = 1:n
x = a + (j-0.5)*h;
I = I + h*f(x);
end
end

Star Strider on 8 Sep 2021
See if ‘func2’ (without the loop) does what you want.
f = @(x) exp(-0.1*x) .* sin(2*pi*x);
a = -5;
b = 5;
n = 10;
I = func(f,a,b,n)
I = -2.0704e-15
I = func2(f, a, b, n)
I = -2.0704e-15
function I = func(f, a, b, n)
% Add description, name, date, inputs, outputs
h = (b-a)/n;
I = 0;
for j = 1:n
x = a + (j-0.5)*h;
I = I + h*f(x);
end
end
function I = func2(f, a, b, n)
h = (b-a)/n;
j = 1:n;
x = a + (j-0.5)*h;
I = sum(h*f(x));
end
Experiment to get different results.
.
Star Strider on 8 Sep 2021
My pleasure!
.

Rik on 8 Sep 2021
What you want is not possible. Depending on what f is there might be ways to avoid the loop and use vector-operations instead, but a general solution is not possible.
It is a misconception that loops are always slower. They can be faster, especially when comparing to cellfun or arrayfun, which just hide the loop. The only situation where a loop is faster, is when there is a direct function. Instead of looping through a vector and using +, you can use sum. Or instead of nested loops you might be able to use conv.
For your case there isn't a general solution, because f is unknown, and the variables resulting in x are not guaranteed to result in a scalar.

Jan on 8 Sep 2021
Edited: Jan on 8 Sep 2021
Does f() accept a row vector as input? Does it reply a row vector or matrix then? If so:
function I = func(f, a, b, n)
h = (b - a) / n;
x = a + (0.5:(n - 0.5)) * h;
I = h * sum(f(x), 2);
end
Haider Ali on 8 Sep 2021
Thanks alot