2014-10-04 39 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