Effacer les filtres
Effacer les filtres

Replacing for loop in the function

2 vues (au cours des 30 derniers jours)
Haider Ali
Haider Ali le 8 Sep 2021
Commenté : Star Strider le 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

Réponse acceptée

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

Connectez-vous pour commenter.

Plus de réponses (2)

Rik
Rik le 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 le 8 Sep 2021
Modifié(e) : Jan le 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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by