2013-03-22 49 views
1

這與How to retrieve local variables?有關,但範圍更廣。是否有可能通過matlab函數來自動比較函數中局部變量的值?

該場景看起來像這樣。假設我有兩個功能

function [OutA OutB OutC] = F1 (x,y,z) 
    local1 = x + y - z %some arbitrary computation 
    local2 = x - y + z %other computation 
end 

function [OutA OutB OutC] = F2 (x,y,z) 
    local1 = x+ y %some computation 
    local2 = x - y %other computation 
end 

我想編寫,將採取F1 F2 x y z "local1" "local2"作爲輸入的功能,和每一個與輸入x y z執行期間返回1如果local1F1F2local2匹配。

是否可以在Matlab中完成此操作,理想情況下無需修改原始功能? 我猜這是關於函數是否是Matlab中的第一類對象的問題,我嘗試Google但未找到它。

回答

1

由於函數的內部變量是私有的(除非將它們設置爲全局變量或返回變量),如果不更改函數或將它們放入更大的函數中,這是不可能的。

的正確方法是將它們設置爲迴歸變量(因爲你如何使用它們的局部變量實際上定義返回變量):

function retval = compareLocals(x,y,z) 
    [~, ~, ~, local1a, ~] = F1 (x,y,z); 
    [~, ~, ~, ~, local2b] = F2 (x,y,z); 
    retval = double(local1a=local2b); 
end 



function [OutA, OutB, OutC, local1, local2] = F1 (x,y,z) 
    local1 = x + y - z %some arbitrary computation 
    local2 = x - y + z %other computation 
end 
function [OutA, OutB, OutC, local1, local2] = F2 (x,y,z) 
    local1 = x+ y %some computation 
    local2 = x - y %other computation 
end 

或嵌套函數也是一種選擇(但已經劈十歲上下IMO):

function retval = compareLocals(x,y,z) 
    F1 (x,y,z); 
    F2 (x,y,z); 
    retval = double(local1a=local2b); 


    function [OutA OutB OutC] = F1 (x,y,z) 
     local1a = x + y - z %some arbitrary computation 
     local2a = x - y + z %other computation 
    end 

    function [OutA OutB OutC] = F2 (x,y,z) 
     local1b = x+ y %some computation 
     local2b = x - y %other computation 
    end 
end 

,併爲此目的使用全局變量似乎只是錯誤的(但話又說回來,中global variables is usually bad practice的整體思路)。