Replacing for loop in the function

8 次查看(过去 30 天)
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?
Thanks alot in advance.
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
Star Strider 2021-9-8
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.
.
  2 个评论
Haider Ali
Haider Ali 2021-9-8
thanks alot. it worked perfect. you are a life saviour
Star Strider
Star Strider 2021-9-8
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

请先登录,再进行评论。

更多回答(2 个)

Rik
Rik 2021-9-8
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
Jan 2021-9-8
编辑:Jan 2021-9-8
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by