我正在尝试调用数值积分函数(即使用梯形方法的函数)来计算定积分。但是,我想将多个'n'值传递给以下函数,
function I = traprule(f, a, b, n)
if ~isa(f, 'function_handle')
error('Your first argument was not a function handle')
end
h = (b-a)./ n;
x = a:h:b;
S = 0;
for j = 2:n
S = S + f(x(j));
end
I = (h/2)*(f(a) + 2*S + f(b)); %computes indefinite integral
end
我正在使用; f = @(x) 1/x
,a = 1
和b = 2
。我也试图传递n = 10.^(1:10)
,但是,当我这样做时,我得到I
的以下输出,
I =
Columns 1 through 3
0.693771403175428 0.069377140317543 0.006937714031754
Columns 4 through 6
0.000693771403175 0.000069377140318 0.000006937714032
Columns 7 through 9
0.000000693771403 0.000000069377140 0.000000006937714
Column 10
0.000000000693771
关于如何使函数获取n = 10.^(1:10)
的任何想法,所以我得到类似的输出,
I = 0.693771403175428,0.693153430481824,0.693147243059937 ......依此增加10的功率?
答案 0 :(得分:0)
在您调用此脚本的脚本中,只需遍历n
k = 3;
f = @(x)1./x;
a = 1; b = 2;
I = zeros(k,1);
for n = 1:k
I(n) = traprule(f, a, b, 10^n);
end
% output: I = 0.693771403175428
% 0.693153430481824
% 0.693147243059937
然后I
将包含所有输出。或者,您可以调整函数以使用相同的逻辑来循环传递n
的元素
作为载体。
注意,您可以通过删除traprule
循环来提高for
代码的效率:
% This loop operates on every element of x individually, and is inefficient
S = 0;
for j = 2:n
S = S + f(x(j));
end
% If you ensure you use element-wise equations like f=@(x)1./x instead of f=@(x)1/x
% Then you can use this alternative:
S = sum(f(x(2:n)));