繁体   English   中英

将函数作为参数传递给函数

[英]Pass function as argument to function

因此,我将这两个文件组成了.m文件。 这是我遇到的问题的一个例子,数学是伪数学

rectangle.m:

function [vol, surfArea] = rectangle(side1, side2, side3)
vol = ...;
surfArea = ...;
end

ratio.m:

function r = ratio(f,constant)
% r should return a scaled value of the volume to surface area ratio 
% based on the constant provided.

% This line doesn't work but shows what I'm intending to do.
[vol,surfArea] = f

r = constant*vol*surfArea;
end

我不确定该怎么做是将矩形函数作为f传递,然后从ratio函数内部访问vol和surfArea。 我已经阅读了有关函数句柄和函数的Mathworks页面,并空手弄清楚如何做到这一点。 我是MATLAB新手,所以也无济于事。

让我知道您是否需要更多信息。

谢谢!

传递函数rectangle as和ratio参数的正确方法是

r = ratio( @recangle, constant )

然后[vol,surfArea] = f(s1,s2,s3)您可以从ratio内调用[vol,surfArea] = f(s1,s2,s3) ,但这需要sideX参数。

如果ratio不需要了解这些参数,则可以创建一个对象函数并将其作为参考参数传递。 或者更好的是,您可以完全创建一个矩形类:

classdef Rectangle < handle

    properties
        side1, side2, side3;
    end

    methods

        % Constructor
        function self = Rectangle(s1,s2,s3)
        if nargin == 3
            self.set_sides(s1,s2,s3);
        end
        end

        % Set sides in one call
        function set_sides(self,s1,s2,s3)
            self.side1 = s1;
            self.side2 = s2;
            self.side3 = s3;
        end

        function v = volume(self)
            % compute volume
        end

        function s = surface_area(self)
            % compute surface area
        end

        function r = ratio(self)
            r = self.volume() / self.surface_area();
        end

        function r = scaled_ratio(self,constant)
            r = constant * self.ratio();
        end

    end

end

尽管我没有在上面的问题中提到这个问题,但这是我一直在寻找的问题。

因此,我想做的是将一些矩形参数传递给ratio,同时能够从ratio函数内操纵任意数量的矩形参数。 给定我上面的.m文件,第三个.m看起来像这样。 该解决方案最终使用了MATLAB的匿名函数

CalcRatio.m:

function cr = calcRatio(length)
% Calculates different volume to surface area ratios given
% given different lengths of side2 of the rectangle.
cr = ratio(@(x) rectangle(4,x,7); %<-- allows the 2nd argument to be 
                                  % manipulated by ratio function
end

ratio.m:

function r = ratio(f,constant)
% r should return a scaled value of the volume to surface area ratio 
% based on the constant provided.

% Uses constant as length for side2 - 
% again, math doesnt make any sense, just showing what I wanted to do.
[vol,surfArea] = f(constant);

r = constant*vol*surfArea;
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM