我有一些我想要一堆函式使用的錯誤處理代碼,所以為了避免重復,我想我會把它放在我的通用類中,其中包含實用函式FunctionContainer。
這是 的截斷版本FunctionContainer:
classdef FunctionContainer
methods (Static)
function run(func, ExpInfo, logdir, newdir, varargin)
try
func(ExpInfo, newdir, varargin)
catch ME
FunctionContainer.errproc(logdir, newdir, ME)
end
end
function errproc(logdir, newLogDir, ME)
errdir = fullfile(logdir, 'error');
movefile(newLogDir, errdir);
pathParts = strsplit(newLogDir, filesep);
logID = pathParts(end);
newLogText = fullfile(errdir, logID, 'error.txt');
fid = fopen(newLogText, 'wt');
fprintf(fid, '%s\n%s\n', ME.identifier, ME.message);
for i = 1:length(ME.stack)
fprintf(fid, '%i\t%s\n', ME.stack(i).line, ...
ME.stack(i).file);
end
fclose(fid);
rethrow(ME);
end
function newdir = prolog(logdir, id, supfiles)
id = join([id, string(clock)], '_');
newdir = fullfile(logdir, id); mkdir(newdir)
stack = dbstack('-completenames');
files = horzcat({stack.file}, supfiles);
for i = 1:numel(files)
copyfile(files{i}, newdir)
end
end
end
結尾
這是我使用它的背景關系:
function realign(ExpInfo)
fc = FunctionContainer;
logdir = ExpInfo.logdir;
ws = fullfile(logdir, 'workspace.mat'); save(ws);
newdir = fc.prolog(logdir, 'realign', {ws});
fc.run(runRealign, ExpInfo, logdir, newdir);
function runRealign(ExpInfo, newdir)
% do a bunch of stuff
end
end
ks_main.m我的腳本中呼叫的相關行realign是
realign(FullData)
我收到此錯誤:
8 fc.run(runRealign, ExpInfo, logdir, newdir);
Error using realign/runRealign
Too many output arguments.
Error in realign (line 8)
fc.run(runRealign, ExpInfo, logdir, newdir);
Error in ks_main (line 35)
realign(FullData)
在這種情況下,我只是不明白這個錯誤。這些函式都沒有回傳任何東西或有任何輸出。如果 runRealign 輸入過多,我也許可以理解,我嘗試runRealign像這樣定義
function runRealign(ExpInfo, newdir, varargin)
但這并沒有什么不同。也許這與將函式作為引數傳遞給另一個函式有關?在 Matlab 中執行此操作的正確方法是什么?
uj5u.com熱心網友回復:
您需要將@符號放在函式引數的前面fc.run。將函式句柄作為引數傳遞時始終執行此操作(https://au.mathworks.com/help/matlab/matlab_prog/pass-a-function-to-another-function.html)。realing.m 的第 8 行應該是:
fc.run(@runRealign, ExpInfo, logdir, newdir);
還有其他幾個問題。一個是你end在結尾缺少一個FunctionContainer。這可能只是您問題中的一個錯字,否則您也會遇到與此相關的錯誤。
logdir另一個小的實作細節是,如果它無論如何都將成為一個欄位,則不需要將其用作引數ExpInfo-您可以簡單地從ExpInfo內部訪問它,FunctionContainer而無需將其顯式傳遞給run. 將兩者ExpInfo及其欄位傳遞logdir給同一個函式是不清楚的,并且在風格上是不好的做法。(這提醒我,你也應該FullData在你的問題中提供一個定義。我必須辨別它需要這個欄位。)
但是,這是代碼,也會導致在FunctionContainer. 的定義runRealign只需要 2 個引數,但是當您try在其中運行它時,FunctionContainer您期望 3: func(ExpInfo, newdir, varargin)。如果我將第 6 行更改FunctionContainer為:
func(ExpInfo, newdir)
有用。
為了使這個健壯和無錯誤,您需要決議varargininFunctionContainer以便它智能地處理可變數量的引數(https://au.mathworks.com/help/matlab/ref/varargin.html),或者保證輸入函式句柄指向一個永遠和永遠有 2 個引數的函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/446585.html
