创建函数的两种方式
(1)m文件
(2)匿名函数
按照书本的步骤进行的
(1)
下面是我的function文件
function y = ellipse(x)
y = sqrt(9-x^2);
并保存名字为‘ellipse’的m文件里面
下面是命令窗口运行的
原命令函
>> y = ellipse(4)
y =
0.0000 + 2.6458i
定义和调用匿名函数
>> f = @ ellipse;
>> y = f(4)
>> y = f(4)
y =
0.0000 + 2.6458i
(2)
直接创建匿名函数
公式要紧跟在后面,syntax是两部分:第一部分 是 @(变量名1,变量名2,。。);第二部分是 包含变量的函数命令,即字符串格式的函数句柄
>> ellipse = @(x)sqrt(9-x^2)
ellipse =
@(x)sqrt(9-x^2)
访问一下数据结构
>> whos ellipse
Name Size Bytes Class Attributes
Name Size Bytes Class Attributes
ellipse 1x1 32 function_handle
>> ellipse(4)
ans =
0.0000 + 2.6458i
如果没有输入的变量,则在输入变量的括号中用空格代替
>> show = @() disp('hello')
show =
@()disp('hello')
>> show = @( ) disp('hello')
show =
@()disp('hello')
>> show()
hello
>> show
hello
>> show
show =
@()disp('hello')