Overloaded function causes Matlab to hang
3 次查看(过去 30 天)
显示 更早的评论
I needed to compile some code in an old version of Matlab for a customer and one builtin function wasn't supported in 2014b and, since it's a trivial function, I wrote something with same name that would do the same task. I thought I may as well keep it in the main code so wrote it such that it would use the builtin in later Matlab. It worked fine in 2014b and 2018b when I tested it, albeit with warning about same name as a builtin when run in 2018b.
But then I found out that with it on the path, later versions of Matlab won't even launch, they give the warning during Initializing and then hang. I tested this in 2018b and 2020a. Can someone advise why this might be?
Here's the code:
function TF = startsWith(str,pattern,~,ignoreCase)
% Temporary overload of builtin startsWith so that command can be used in
% compiled Matlab 2014b code
if nargin < 4
ignoreCase = false;
end
if ~verLessThan('matlab','9.1') % 2016b
TF = builtin('startsWith',str,pattern,'IgnoreCase',ignoreCase); % call builtin
else
str = str(1:min([length(str), length(pattern)]));
if ignoreCase
str = lower(str);
pattern = lower(pattern);
end
TF = isequal(str,pattern);
end
What did I do wrong?
0 个评论
采纳的回答
Matt Kuranda
2020-11-18
This is a shadowing problem. On startup, Matlab runs matlabrc, which does all sorts of initialization. Somewhere in that initialization code, startsWith gets called, which in turn calls your version of startsWith because it is shadowing the builtin version.
In your function, it looks like somewhere in the process of executing the line where you call the builtin explicitly, startsWith gets called again by an M code helper function (some path-related function), which again uses your version of startsWith, and ends up in an infinite recursion that causes Matlab to hang. This is one of the dangers of shadowing commonly used builtins, it's often not obvious what kinds of MathWorks helper M code will end up calling them, and could cause Matlab to work in unintended ways.
A potential workaround for you here would be to rename your function to something other than startsWith so it no longer shadows the builtin, and then use your renamed function in place of startsWith in your code.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!