MATLAB function f(x) 代入問題

2008-04-24 8:31 pm
以下function是用midpoint rule計算出積分f(x)

function Q4(f,n,a,b)
h = (b-a)/n;
S=0;
for k = 1:n,
S = S+f(a+h*(k-1/2));
end
S = h*S

把數值代入函數f(x)時出現了
Attempted to access f(0.5); index must be a positive integer or logical.

請問該如何把非整數數值代入方程f(x)呢?
更新1:

但f是用戶在call function時輸入的argument 那該如何處理?

回答 (1)

2008-04-24 9:14 pm
✔ 最佳答案
唔係非整數數值o既問題
因為佢唔係當你個f係function
佢以為你個0.5係做緊array index
咁個array又點會有第0.5個數呢?

你應該define f做一個anonymous function
例如f = @(x) x^2
咁你打f(0.5)佢就會幫你計到係0.2500喇



2008-04-26 06:43:27 補充:
我俾你個f咪就係用o黎做input argument囉
你個f複雜o的o既話你可以define 佢用另一個function

2008-04-26 06:44:21 補充:
2 more changes for your Q4:

function [S] = Q4(f,n,a,b)
S = h*S;


收錄日期: 2021-04-23 21:13:17
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20080424000051KK00780

檢視 Wayback Machine 備份