是否有一种优雅的方式告诉matlab在执行某个脚本中的每一行后执行预定义的操作?优雅我的意思是在每一行之后都没有调用动作,而是在脚本开头给出一个简单的命令。
实施例:
行动 - > disp('Performing Action');
脚本:
a = 1;
b = 2;
c = 3;
所以理想的结果是在每次赋值(a,b和c)之后,将执行disp()命令。
答案 0 :(得分:5)
您可以自动创建一个修改过的文件,其中包含每行末尾所需的操作:
action = 'disp(''Performing Action'');'; %// action to be added at the end of each line
file = 'script.m'; %// original script
file_out = 'script_out.m'; %// modified script with action added
x = importdata(file); %// cell array of strings. Each line of the
%// original file is a string
x = strcat(x, {' ; '}, action); %// add action at the end of each string,
%// preceded with `;` in case the original line
%// didn't include that
fid = fopen(file_out, 'w');
fprintf(fid, '%s\n', x{:}); %// write output file
fclose(fid);
答案 1 :(得分:1)
a = 1;
disp('Performing Action');
b = 2;
disp('Performing Action');
c = 3;
disp('Performing Action');
或者,如果你可以循环
for ii = 1:3
a(ii) = ii;
disp('Performing Action');
end
实际上在每行之后输出一些东西不是很matlab,但你当然可以松开所有的分号,这样如果你想跟踪脚本中的位置,就会显示所有变量。
我建议您在代码中进行verbose
切换。将其设置为0表示无输出,1表示输出(如果需要,则设置为多个级别)
if verbose > 0
disp('Performing Action');
end
这样,您可以根据需要轻松打开或关闭输出。
有关代码阅读和附加内容,请参阅https://stackoverflow.com/a/32137053/5211833上的Louis Mendo的回答
答案 2 :(得分:1)
这是我的尝试。你可以:
注意强>
for
,if
等的函数。runEachLine
(以及feval
)来改进代码。这是一个代码示例(部分基于this):
foo.m
function foo(args)
a = args{1};
b = 2;
c = a + b;
end
runEachLine.m
function runEachLine( mfile, args )
if nargin < 1
error('No script m-file specified.');
end
if ~strcmp(mfile(end-1:end),'.m')
mfile = [mfile '.m'];
end
if ~exist(mfile,'file')
error(['Cannot access ' mfile])
end
% Read function file
M = textread(mfile,'%s','delimiter','\n');
% Remove empty lines
M = M(~cellfun('isempty',M));
% Input arguments
assignin('base', 'args', args);
% Skipping first line: function [...] = func_name(...)
% Skipping last line : end
for k=2:length(M)-1
try
% Execute each line
evalin('base',M{k})
% Execute your custom function
disp(['Performing Action: ' M{k}]);
catch ME
error('RunFromTo:ScriptError',...
[ME.message '\n\nError in ==> ' mfile ' at ' num2str(k) '\n\t' M{k}]);
end
end
end
用法:
>>runEachLine('foo.m', {4});
结果:
>> runEachLine('foo.m', {4})
Performing Action: a = args{1};
Performing Action: b = 2;
Performing Action: c = a + b;
>>
答案 3 :(得分:-2)
不,没有。
您在原始问题中提供的内容只是=
运算符的简单用法。
如果要重载MATLAB的默认行为,则应考虑创建一个类,并为每个所需的操作符或函数定义所需的行为。