matlab几种创建函数的方法

创建函数的几种方法

1在.m 文件中创建,可以是函数文件,也可以是脚本文件

Function [output1, output2,output3...]=MyFunction_name(arg1,arg2...)
	implement;
	...
	end

举例:
求方程的根

现在在创建.m 文件输入下面的程序

function [x1, x2, D]=QUAD(a, b, c) % QUAD.m
% Solves quadratic equations based on coefficients of: a, b, c
% Note that a, b, c need to be scalars. 
fprintf('Solve: (%g)x^2+(%g)x+(%g)=0\n', a,b,c)
D=b^2-4*a*c; 
% Roots
x1=(-b+sqrt(D))/(2*a); 
x2=(-b-sqrt(D))/(2*a);
if lt(D,0)
fprintf('This equation does not have real value roots!\n'); 
fprintf('Because discriminant is negative. D = %g\n', D); 
fprintf('Complex Root1: x1= %10s\n', num2str(x1)); 
fprintf('Complex Root2: x2= %10s\n', num2str(x2)); 
elseif eq(D,0)
disp('This equation has one unique root! '); 
disp('Because discriminant is zero. D=0 '); 
fprintf('This equation has one unique root! \n'); 
fprintf('Because discriminant is zero. D=0 \n'); 
fprintf('Unique Root: x = %g \n', x1);
else
fprintf('This equation has two roots \n'); 
fprintf('Because discriminant is: D = %g \n', D); 
fprintf('Root1 of the equation is: x1= %g \n', x1); 
fprintf('Root2 of the equation is: x2= %g \n', x2);
end

搞完之后你就可以在command window 里调用这个函数了

>> [x1, x2, D]=QUAD_01(1, 2, 3)

2.Function_handler(@)创建匿名函数

Function_handler=@(arg1,arg2,arg2...)([expression1,expression2...])

举例:
在这里插入图片描述

在command window 中输入

>> f_handle = @(t)(sin(2*t)./exp(2*t)); 现在这个匿名函数有个别名叫f_handle
>> t=linspace(0,2*pi, 100);%02*pi 中切分成100>> f=f_handle(t); plot(t, f, 'o-')

@是函数句柄,其实就是函数别名或者理解成函数指针

3.inline 函数内联函数

f=inline('[expression1; expression2, ...]','arg1','arg2','arg3', ...);

举例
在这里插入图片描述

>> F = inline('[exp(2*t.*theta); sin(2*t)]', 't', 'theta');
>> t=0:pi/20:pi; theta=linspace(0,1,length(t));
>>fcalc=F(t, theta)
>>plot(t, log(F(t, theta)), 'linewidth', 1.5);

4.利用syms 和 matlabfunction 创建在这里插入图片描述

syms u1 u2  
% Define variables (input data names)
% Formulate the given function equations f=[u2-exp(2*u1), 1.25*u1-exp(3*u2)];
% Define a function file name, e.g. myFUN
matlabFunction(f, 'file', 'myFUN');

然后你就建立了一个叫myFUN 的函数(实际上是个.m文件),里面长这个样,奇怪的为什么最后不用加end?其实也就是创建了一个文件

function f = myFUN(u1, u2) %MYFUN
% F = MYFUN(U1,U2)
% This function was generated by the Symbolic Math Toolbox version 5.9 %
24-Apr-2013 14:20:01
f = [u2-exp(u1.*2.0),u1.*(5.0./4.0)-exp(u2.*3.0)];
  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值