Replacing for loop in the function

9 Ansichten (letzte 30 Tage)
Haider Ali
Haider Ali am 8 Sep. 2021
Kommentiert: Star Strider am 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?
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

Akzeptierte Antwort

Star Strider
Star Strider am 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.
.
  2 Kommentare
Haider Ali
Haider Ali am 8 Sep. 2021
thanks alot. it worked perfect. you are a life saviour
Star Strider
Star Strider am 8 Sep. 2021
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Rik
Rik am 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
Jan am 8 Sep. 2021
Bearbeitet: Jan am 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by