Why do I get a different result when running code in editor vs. in command window?
16 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
Infinite_king
2023-12-4
编辑:Infinite_king
2023-12-4
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!