Replacing for loop in the function

7 ビュー (過去 30 日間)
Haider Ali
Haider Ali 2021 年 9 月 8 日
コメント済み: Star Strider 2021 年 9 月 8 日
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
  1 件のコメント
Haider Ali
Haider Ali 2021 年 9 月 8 日
Thanks alot

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by