我有一些错误处理代码,我想要一堆函数使用,所以为了避免重复,我想我应该把它放在保存实用函数 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
的相关行是
重新对齐(完整数据)
我收到此错误:
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
函数 runRealign(ExpInfo, newdir, varargin)
但这没有什么区别。也许这与将一个函数作为参数传递给另一个函数有关?在 Matlab 中执行此操作的正确方法是什么?
最佳答案
您需要将@
符号放在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);
还有一些其他问题。一是您在 FunctionContainer
末尾缺少 end
。这可能只是您问题中的一个拼写错误,否则您也会遇到与此相关的错误。
另一个小的实现细节是,如果 logdir
无论如何都会成为 ExpInfo
中的字段,则您不需要使用 logdir
作为参数 — 您可以只需从 FunctionContainer
内部的 ExpInfo
访问它,而不必将其显式传递给 run
。将 ExpInfo
及其字段 logdir
传递给同一个函数是不明确且风格上不好的做法。 (这提醒我,您还应该在问题中提供 FullData
的定义。我必须辨别它需要此字段。)
但是,这是代码,因为它也会导致在 FunctionContainer
第 6 行引发异常。 runRealign
的定义只需要 2 个参数,但是当您尝试
在 FunctionContainer
中运行它时,您期望 3 个:func(ExpInfo, newdir、varargin)
。如果我将 FunctionContainer
的第 6 行更改为:
func(ExpInfo, newdir)
它有效。
为了使其健壮且无错误,您需要解析 FunctionContainer
中的 varargin
,以便它智能地处理可变数量的参数 ( https://au.mathworks.com/help/matlab/ref/varargin.html ),或者否则保证输入函数句柄永远指向一个有 2 个参数的函数句柄。
关于matlab - 在 Matlab 中将函数传递给另一个函数时出现“输出参数太多”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71504958/