2016-05-29 64 views
-1

我想寫一個近似梯形法則積分的函數。在Matlab中的兩個函數來近似積分 - 沒有足夠的輸入參數?

我首先在一個文件中定義的函數:

function[y] = integrand(x) 
y = x*exp(-x^2); %This will be integrand I want to approximate 
end 

然後我寫函數近似定積分與下界和上界B(也在另一文件):

function [result] = trapez(integrand,a,b,k) 

sum = 0; 
h = (b-a)/k; %split up the interval in equidistant spaces 

for j = 1:k 
    x_j = a + j*h; %this are the points in the interval 
    sum = sum + ((x_j - x_(j-1))/2) * (integrand(x_(j-1)) + integrand(x_j)); 

end 
result = sum 
end 

但是當我想從命令窗口調用這個函數時,例如使用result = trapez(integrand,0,1,10),我總是會得到一個錯誤'沒有足夠的輸入參數'。我不知道我做錯了什麼?

回答

2

有你的代碼許多問題:

  • x_(j-1)沒有定義,而不是真的是一個有效的Matlab語法(假設你希望它是一個變量)。
  • 通過調用trapez(integrand,0,1,10)你實際上調用integrand函數沒有輸入參數。如果您想要傳遞句柄,請改用@integrand。但在這種情況下,根本不需要傳遞它。
  • 您應該避免與Matlab函數一致的變量名稱,例如sum。如果您也嘗試使用sum作爲函數,這很容易導致難以調試的問題。

這裏有一個工作版本(注意也更好的代碼風格):

function res = trapez(a, b, k) 
    res = 0; 
    h = (b-a)/k; % split up the interval in equidistant spaces 

    for j = 1:k 
     x_j1 = a + (j-1)*h; 
     x_j = a + j*h; % this are the points in the interval 
     res = res+ ((x_j - x_j1)/2) * (integrand(x_j1) + integrand(x_j)); 
    end 
end 

function y = integrand(x) 
    y = x*exp(-x^2); % This will be integrand I want to approximate 
end 

,並呼籲事情是這樣的:result = trapez(0, 1, 10);

+0

+1,但是,「但在這種情況下,根本不需要傳遞它。」只有當'integrand'在路徑上時纔是真實的,否則它恰好是對傳入的函數句柄的調用 - 使用具有相同名稱的參數是一個壞主意。 – horchler

+0

將函數'sum'作爲變量名覆蓋常見也是不好的做法。 – horchler

+0

謝謝。我應該給文件什麼名字? – Kamil

0

integrand函數需要輸入參數x,你是不是在你的命令行函數調用提供

+0

我只是去嘗試。我收到錯誤'未定義的函數或變量'x'。' ? – Kamil

+0

我認爲問題與積分功能有關。如果我想運行它,它總是說x是未定義的。我不明白 – Kamil

相關問題