2017-05-25 87 views
0

我想调用一个数值积分函数(即使用trapazoidal方法)来计算一个定积分。但是,我想将多个'n'值传递给以下函数:试图获得一个MATLAB函数采取一个输入数组

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/xa = 1b = 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

在您致电该脚本,只需遍历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的元素。


注意,您可以通过删除for循环提高你traprule代码的效率:

% 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 [email protected](x)1./x instead of [email protected](x)1/x 
% Then you can use this alternative: 
S = sum(f(x(2:n))); 
+0

当我运行一个循环中,无限循环。我自己有以下循环开始, 'f = @(x)1/x; a = 1; b = 2; I =零(1,10);对于j = 1:10 I(j)= traprule(f,a,b,10^j); end' –

+0

我纠正了我的代码,它适用于'k = 3' – Wolfie

+0

你知道为什么它不适用于较大的k值,即10吗? –

相关问题