matlab快速入门(24):普通函数

在MATLAB中,函数定义在单独的文件。文件函数的文件名应该是相同的。

函数语句的语法是:

  function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)

 

任务:

下述有个 mymax 函数,它需要五个数字作为参数并返回最大的数字。

建立函数文件,命名为 mymax.m 并输入下面的代码:

 

 

function max = mymax(n1, n2, n3, n4, n5)
%This function calculates the maximum of the
% five numbers given as input
max =  n1;
if(n2 > max)
    max = n2;
end
if(n3 > max)
   max = n3;
end
if(n4 > max)
    max = n4;
end
if(n5 > max)
    max = n5;
end

每个函数的第一行要以 function 关键字开始。它给出了函数的名称和参数的顺序。

在我们的例子中,mymax 函数有5个输入参数和一个输出参数。

注释行语句的功能后提供的帮助文本。这些线条打印,当输入:

 

help mymax

  

 

 

可以调用该函数:

 

 



posted @ 2021-07-31 01:18  川川菜鸟  阅读(299)  评论(0编辑  收藏  举报