问一道matlab的题目

来源:百度知道 编辑:UC知道 时间:2024/07/04 09:22:48
Give the m-file to implement the function avgfun which takes the name of a function and a vector as arguments and returns the average of the function values evaluated at the vector. For a function f and for a vector x of size n, avgfun returns 1/nf(xi)
请给出在m-file中详细的代码解答,谢谢!

function mu=avgfun(f,x)
n=length(x);s=0;
for i=1:n
s=s+f(x(i));
end
mu=s/n;

把上面的代码保存为avgfun.m即可

例子:
在matlab界面中输入

f=inline('x^2');
avgfun(f,1:5)%求1、4、9、16、25的平均值

例二:
avgfun(@sin,[0,pi/6,pi/4,pi/3,pi/2])%求sin(0)、sin(pi/6)、sin(pi/4)、sin(pi/3)、sin(pi/2)的平均值

例三:
avgfun(@(x)2*x,1:3)%求2、4、6的平均值

取N阶向量X的每一个元素Xi(i=1,2,3……n)作为自变量求函数值,然后求这n个值的平均数

X=[X1 X2 X3 X4 X5……Xn],f=f(x)

avgfun=1/n*f(Xi)(i=1,2,3,……n)