我可以在matlab中使用控制结构中的子功能吗?

时间:2014-03-14 13:40:44

标签: matlab

这是该计划。

我需要使用子功能来完成这项工作。

%//To compute the area of circle,rectangle or volume of rectangle depending on the number of input arguments.

y=areavlme(a,b,c)    

%//For one input, the function finds the area for the circle
%//For two inputs, finds the area of rectangle
%//For three inputs, finds the volume of rectangle

if nargin<1
    disp('error');
elseif nargin==1
    function s = circarea(a);
        s=a*a;
elseif nargin==2
    function t =rectarea(a,b);
        t=a*b;
else
    function e=rectvolume(a,b,c);
        e=a*b*c;

3 个答案:

答案 0 :(得分:3)

同样,我不明白这一点,但您可以使用匿名函数。

circarea = @(x) pi*x*x;
rectarea = @(x,y) x*y;
rectvolume = @(x,y,z) x*y*z;

if nargin<1
    disp('error');
elseif nargin==1
    s=circarea(a);
elseif nargin==2
    t = rectarea(a,b);
else
    e = rectvolume(a,b,c);

假设a是半径,那么圆的面积方程式将需要pi。

答案 1 :(得分:2)

我不明白这一点。

您有以下选择:

  • 无功能操作:

    function y=areavlme(a,b,c)
    
    if nargin<1
        disp('error');
    elseif nargin==1
        y = a*a;
    elseif nargin==2
        y = a*b;
    else
        y = a*b*c;
    
  • 使用函数进行操作并调用它们

    function y=areavlme(a,b,c)  
    
    if nargin<1
        disp('error');
    elseif nargin==1
        y = circarea(a);
    elseif nargin==2
        y = rectarea(a,b);
    else
        y = rectvolume(a,b,c);
    
    function s = circarea(a);
    s=a*a;
    
    function t =rectarea(a,b);
    t=a*b;
    
    function e=rectvolume(a,b,c);
    e=a*b*c;
    

答案 2 :(得分:0)

另一种方法是使用嵌套函数,利用作用域来删除函数调用中的参数

function y=areavlme(a,b,c)

%//For one input, the function finds the area for the circle
%//For two inputs, finds the area of rectangle
%//For three inputs, finds the volume of rectangle

function s = circarea
    s=a*a*pi;
end

function t =rectarea
    t=a*b;
end

function e=rectvolume
    e=a*b*c;
end


if nargin<1
    disp('error');
elseif nargin==1
    y=circarea;
elseif nargin==2
    y=rectarea;
else
    y=rectvolume;
end
end