MATLAB 第六章 M文件与函数句柄

一、脚本文件和函数文件

image
M文件分为脚本文件(命令文件)和函数文件

特点

image

脚本文件

数据输入

输入数值变量:A = input('提示信息')
输入字符串变量:A = input('提示信息','s')

数据输出

输出数值变量:disp(X)
输出字符串变量:disp('X')
格式化输出:fprintf(format,A,...)
image

取整函数

image

函数文件

image

创建事项

image

function [s,p] = fcircle(r)
s = pi*r*r;
p = 2*pi*r;
end

调用事项

image

r = input('r:');
[s,p] = fcircle(r);
disp(s);
disp(p);

局部变量与全局变量

局部变量

image

全局变量

image

函数中修改全局变量

image

二、函数类别

主函数与子函数

image

function c = test(a,b) % 主函数
c = test1(a,b)*test2(a,b);

function c = test1(a,b) % 子函数1
c = a + b;

function c = test2(a,b) % 子函数2
c = a - b;
a = input('a:');
b = input('b:');
c = test(a,b);
disp(c);

匿名函数

特点:函数很简单不需要创建M文件**

格式

FH = @(xlist)expression
image
举例:Hy = @(x)sin(x).*log(x)

fh = @(x)exp(x.*x);
integral(fh,0,1)

调用

直接调用

FH(xlist)

间接调用

feval(FH,xlist)

三、函数句柄

image

创建函数句柄

法一:@+函数名

function fv = fun(x)
	fv = x-10.^x+2;
end
hfun = @fun

法2:str2func(函数名)

hfun = str2func('fun')

四、程序控制流

if-else-end分支结构

单分支

image
image

双分支

image

x = input('x:');
if x<=0
    y = (x+sqrt(pi))/exp(2);
else
    y = log(x + sqrt(1+x.*x));
end
disp(y);

多分支

image

x = input('x:');
if x>=90
    result = 'A';
elseif x>=80
        result = 'B';
elseif x>=70
    result = 'C';
elseif x>=60
    result = 'D';
else
    result = 'E';
end
disp(result);

switch语句

image

x = input('x:');
x=floor(x/10);
switch x
    case {9,10} % 注意:多个条件变量用大括号包围
        ans = 'A';
    case 8
        ans = 'B';
    case 7
        ans = 'C';
    case 6
        ans = 'D';
    otherwise %注意不是default
        ans = 'E';
end
disp(ans);

for循环

image
image

y = 0;
for n=1:1:100
    y =  y + 1/(2*n-1);
end
disp(y);

while循环

image

n = 0;
while 2^n<=100
    n = n + 1;
end
disp(n);

为了提高代码的运行效率,避免 for 循环的使用

其他程序控制语句

image

break与continue

image

posted @   安河桥北i  阅读(202)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示