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!