matlab编程与工程应用(第二版) 第六章 自定义函数 笔记

模块化程序:一个问题分解成几个模块。


如果函数中有子函数的话每个函数末尾写end来结束该函数。


程序:

choice=eoption;


while choice~=4
    switch choice 
        case 1
            explation;
        case 2
            limite;
        case 3
            x=input('please the value for x:');
            expfn(x);
    end
    choice=eoption;
end

function choice=eoption
%用户必须从菜单里面选择一项 不能点击菜单窗口右上角的关闭
%print the menu of option and error-check
%until the user pushes one of the buttons
choice=menu('choose an option','explanation','limnit','exponantioal funtion','exit program');

while choice==0
    disp('error--please choose an button');
    choice=menu('choose an option','explanation','limnit','exponantioal funtion','exit program');
end

function limite
n=askforn;
fprintf('an approximation of e with n=% d is % .2f \n',n,(1+1/n)^n)
end

function outn=askforn
inputn=input('enter the postive integfer for n:')
num2=int32(inputn);
while num2 ~=inputn||num2<0
    inputn=input('enter the postive integfer for n:')
    num2=int32(inputn);
end
outn=inputn; %注意此处不能写成outn=num2貌似int32截取会出现问题
end

function expfn(x)
fprintf('valuse of exp(x) is %.2f \n',exp(x));

n=10
fprintf('approximate exp(x) is  %.2f \n',appex(x,n));

end

function out=appex(x,n)
outval=1;
runprod=1;
for i=1:n
    runprod=runprod*i;
    outval=x^i/runprod+outval;
end
out=outval;
end

持续变量:

用persistent来声明 例如persistent count;那么count就是一个持续变量了。



 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值