2014-10-04 41 views
2

所以我有这两个组成.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,然后从比例函数中访问vol和surfArea。我已阅读并阅读了Mathworks的关于函数句柄和函数功能的页面,并且已经找出了解决此问题的方法。我是MATLAB新手,所以也没有帮助。

让我知道你是否需要任何信息。

谢谢!

+0

可以在'cellfun'但在这个例子中函数作为参数传递,例如,你怎么了如果函数没有得到任何参数,希望函数给出结果? – 2014-10-04 21:06:52

+0

所以我设想(错误地)传递的参数是这样的。 '比(矩形(1,2,3),2)'。但是,我认为这更接近正确的答案。 (@矩形,2)'或'比率(@(x)比率(1,2,3),2)'。在最后两种情况下,我不明白如何访问矩形函数的输出。 – 2014-10-04 21:09:43

+0

你是否真的需要创建某种功能闭包?举例来说,根本不需要函数句柄 - 只需让调用者首先调用它想要的任何“f”,然后将生成的'vol'和'surfArea'作为额外参数传递给'ratio'(即“比例” (矩形(1,2,3),2)'idea) – Notlikethat 2014-10-04 21:47:20

回答

2

传递函数rectangle作为和ratio说法正确的方法是

r = ratio(@recangle, constant) 

那么您还可以从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 
+0

所以这是正确的。然而,我没有提到的一件事(并且没有想到任何人会得到)是我想要继承到比例函数的矩形的一些参数,而其他的我想从比率函数中进行操纵。我会写出我今天想到的,但是为了所有意图和目的,您的解决方案可以正常工作。 – 2014-10-05 03:33:47

1

虽然我没有在上面的问题中提出这个问题,但这正是我所寻找的。

所以我想要做的是传递一些矩形参数的比例,同时能够从比率函数内操纵任何选定数量的矩形参数。鉴于上面的.m文件,第三个.m会看起来像这样。该解决方案最终使用MATLAB's anonymous functions

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