Why do I get a different result when running code in editor vs. in command window?

34 visualizaciones (últimos 30 días)
Hi,
I have a very strange bug which I cant seem to fix. When I run the following code in either the editor or the command window I get different results. One results in a simple cell array of doubles (when running in editor window) and one results in a array of complex doubles (when running in command window).
The code is:
pre_h_hursts = zeros(1,length(file_list));
for p = 1:length(file_list)
%head
pre_h_hursts_parts = dfaedit(a_pre_h{1,p},0,0,0);
pre_h_hursts(1,p) = pre_h_hursts_parts;
end
The results of running the code in the editor (as a section within a larger script) are saved in the files "editor_pre_h_hursts.mat" and "editor_pre_h_hursts_parts.mat" and the results from running the code in the command window are saved in the files "command_pre_h_hursts.mat" and "command_pre_h_hursts_parts.mat".
Does anyone have an idea why this is?
EDIT: I also found the that when I run the code in a new editor window in a new script (not part of a longer script) I also get the array of complex doubles as a result.

Respuestas (1)

Infinite_king
Infinite_king el 4 de Dic. de 2023
Editada: Infinite_king el 4 de Dic. de 2023
Hi,
I understand that you are getting different results when you run the script in MATLAB command window and in Editor window.
This is probably because of the Floating-point arithmetic inaccuracies. In MATLAB real values are stored in IEEE Standard 754, or standard floating-point representation. Not every real number can be stored exactly by this format. So, any arithmetic operation on this data type will probably result in addition of little inaccuracy. This will result in different results in different executions.
For example, In ‘dfaedit’ function, let’s consider below expression (line no 64)
s = s + dhh - (dhv*dhv +dhu*dhu*vv - dhv*dhu*BoxSize)*Det;,
Variable ‘s’ is becoming a negative number in some instances, and this was resulting in complex values. These kinds of inaccuracies should be considered while writing code.
Alternatively, ‘sym’ function can be used to work with very large or very small values, but this will increase the runtime considerably.
For more information on Floating points, refer the following MATLAB documentation,
For more information on how to use ‘sym’ function and ‘Symbolic Math Toolbox’, please refer the following MATLAB documentations,
Hope this is helpful.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by