How can a breakpoint affect the result of a computation?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Jan
le 3 Août 2011
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 commentaires
Plus de réponses (1)
Walter Roberson
le 3 Août 2011
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.
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!