Overloaded function causes Matlab to hang

5 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Matt Kuranda
Matt Kuranda il 18 Nov 2020
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.
  1 Commento
Justin
Justin il 19 Nov 2020
OK, thanks, that's useful info, I will do what you suggest.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Startup and Shutdown in Help Center e File Exchange

Tag

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by