1

これは、ローカル変数を取得する方法に関連していますか? 、しかしより広い範囲。

シナリオはこんな感じ。2つの関数があるとします

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

入力として受け取る関数を書きたいと思います。それぞれの実行中にinが入力と一致した場合にF1 F2 x y z "local1" "local2"戻ります。1local1F1local2F2x y z

理想的には元の関数を変更せずに、Matlabでこれを行うことは可能ですか? これに関連して、関数がMatlabのファーストクラスオブジェクトであるかどうかの問題があると思います.Googleで検索しようとしましたが、見つかりませんでした.

4

1 に答える 1

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

そして、この目的でグローバル変数を使用するのは間違っているように思えます (ただし、グローバル変数の全体的な考え方は通常、悪い習慣です)。

于 2013-03-22T08:26:47.730 に答える