【matlab】eps 意义及用法
MATLAB中eps是一个函数,可以返回某一个数N的最小浮点数精度,形式例如eps(N)。一般直接用eps即可。
eps = eps(1) = 2.2204e-16
1 == 1 + eps: false
1 == 1 + eps * 0.51: false
1 == 1 + eps * 0.5: true (<=0.5 时为true)
用法: 一般用在分母上,防止分母等于0。1/(x+eps)。
————————————————
原文链接:https://blog.csdn.net/xuxiaofeng199212/article/details/83143536
Matlab中函数如何定义
自定义函数的途径:
M文件函数(M file function)
在线函数(Inline Function)
匿名函数(Anonymous Function)
1.M文件函数
范例
function c=myadd(a,b)
%这里可以写函数的使用说明,前面以%开头
%在工作区中,help myadd将显示此处的说明
c=a+b;
%end %非必须的
第一行function告诉Matlab这是一个函数,a,b是输入,c是输出,myadd是函数名。以m文件定义的函数必须保存为函数名的形式,上例中,函数应保存为myadd.m。要使用myadd函数,该函数必须在Matlab的搜索路径中。
调用方式:
在Matlab命令符后输入
a=1;b=2;
c=myadd(a,b)
关于m文件定义函数还有许多的说明,暂时略去。。。
2.在线函数(Inline Function)
通常作为参数传递给另外一个函数。比如fminsearch,lsqcurvefit等函数需要以函数作为参数。
在线函数从字符串表达式创建函数,例如:
f=inline(‘x.^2’,‘x’);
创建了函数f(x)=x^2。要计算f(3),在工作区输入f(3)即可。f([2 3 4])计算在x=2 3 4时的值
f=inline(‘x+y’,‘x’,‘y’)
创建了二元函数f(x,y)=x+y,工作区输入f(2,3)计算2+3,等同于feval_r(f,2,3)。
3.匿名函数(Anonymous Function)
匿名函数使用函数句柄来表示匿名函数,定义形式为
函数句柄=@(变量名) 函数表达式
例如:
f=@(x) x.^2
定义了函数f(x)=x^2,f(2)计算在x=2处的值。
匿名函数可以调用Matlab函数,也可以使用工作区中存在的变量,例如
a=2;
f=@(x) x.^2+a
f(2) %计算时引用了变量a
a=0;
f(2) %仍然引用的是a=2
匿名函数也可以由Matlab的内置函数或M文件函数创建,例如
f=@sin %f(x)=sin(x)
f(pi/2) %sin(pi/2)
functions(f) %查看函数信息
利用单元数组可以创建多个函数的句柄,例如
f={@sin @cos}
f{1}(pi/2) %计算sin(pi/2)
f{2}(pi) %计算cos(pi)
函数句柄的另一个重要特征是可以用来表示子函数、私有函数和嵌套函数。
Matlab 7以后,建议以匿名函数取代在线函数!!!
在创建匿名函数时,Matlab记录了关于函数的信息,当使用句柄调用该函数的时候,Matlab不再进行搜索,而是立即执行该函数,极大提高了效率。
此论文转载。
作者:持之以恒7
链接:https://www.jianshu.com/p/4cadb92130a0
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
MATLAB代码实现
clear all;
clc;
format long;
fstr=input('Please enter the function with F-left format: f(x)=','s');
f=inline(fstr);
left=input('Please enter the left value of guess interval: a=') ;
right=input('Please enter the right value of guess interval: b=');
err=input('Please enter the allowed error:');
while f(right)*f(left)>0
disp('Wrong input.\n');
left=input('Please enter the left value of guess interval: a=') ;
right=input('Please enter the right value of guess interval: b=');
err=input('Please enter the allowed error:');
end
a=left;
b=right;
fprintf('k\tInterval\t\tx\tf(x)\n');
for i=1:1000
mp=(right+left)/2;
fprintf('%i\t[%f,%f]\t%f\t%f\n',i,left,right,mp,f(mp));
if f(mp)>0
right=mp;
else
left=mp;
end
if i>(log(b-a)-log(err))/log(2)
break;
end
i=i+1;
end
disp('x=');
——代码源自某大佬同学,吃水不忘挖井人,致敬大佬。