创建函数的几种方法
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);%在0到2*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)];