How can a breakpoint affect the result of a computation?
2 次查看(过去 30 天)
显示 更早的评论
I am debugging and I have a block of code that gives a different answer depending on the location of a breakpoint. The code is included here:
%---compute c1hat---%
c1hat = zeros(size(c));
for i = ind_compute.'
%---make function file---%
fid = fopen(['intgrnd_',funcname,'.m'],'w');
fprintf(fid, '%s \n\n', ['function f = intgrnd_',funcname,'(w,t,p,c)']);
fprintf(fid, '%s \n', ['f = (',funcname,'_hat(w,t,p,c)).*conj(',Zstr{i},').*(0.5).*(sin(w/2).^2).*sin(t);']);
fclose(fid);
%----make function handle---%
integrand = eval(['@(w,t,p) intgrnd_',funcname,'(w,t,p,c);']);
%---perform integration---%
c1hat(i) = simp3D(integrand,0,2*pi,0,pi,0,2*pi,32,32,32);
end
essentially the code just writes a .m function file; makes a function handle to call it with a particular argument, c; and then uses the function handle to perform numerical integration.
If I put a breakpoint on the line that performs the integration and then manually step through each iteration of the for loop by pressing F5 over and over again it gives me the right answer (stored in the variable chat). If instead I put a breakpoint after the for loop to check what is stored in chat I find the wrong answer: specifically, all the elements of chat are the same and equal to the value from the first iteration.
How is it possible that the location of a breakpoint while debugging could alter the results of a computation? And how do I fix this.
Thank you very much for your time!
0 个评论
采纳的回答
Jan
2011-8-3
This is the expected behaviour. If you create an M-file dynamically, it is not reloaded during normal program execution. Therefore this technique is not recommended.
You can force the reloading by
clear(['intgrnd_', funcname]);
0 个评论
更多回答(1 个)
Walter Roberson
2011-8-3
Bad behavior such as this is common when you use eval()
I am not certain that I followed everything, but it appears likely to me that you can avoid these troubles by using anonymous functions, perhaps in conjunction with str2func() . At the moment, I do not see any reason why intgrnd_* needs to be written to a file.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Simulink Functions 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!