Odd behavior with a Simulink reserved name in a function?

Not sure what to make of this. Running R2017a. I have a numeric double precision variable named f14n. I save it to a .mat file. I call a function that loads the mat file with variable f14n in it, and it becomes a Simulink model. This of course crashes the function because I'm treating f14n as a numeric variable. Threw together some ugly code (below) to reproduce what I'm describing. Variable f14n is fine in the calling script, but it launches a Simulink window in the function. Is this a bug or am I breaking a bunch of scripting rules here? Thanks.
f14n=1:10;
save junk.mat f14n
x=10;
dum=junk_func(x);
%%%%%%%%%%
function dum = junk_func(dum2)
load junk.mat
f14n
dum=0

 Respuesta aceptada

Steven Lord
Steven Lord el 19 de Jul. de 2017
Don't "poof" variables into the workspace like that. When MATLAB parsed junk_func it needed to know to what f14n referred. Since there was no indication in the code that it was a variable, and there is a Simulink® model available by that name, it treated that reference as opening that model.

5 comentarios

Jim
Jim el 19 de Jul. de 2017
Thanks for the reply Steven. If I understand things right, all of the variables in the .mat file need to be passed as arguments to the function to avoid "poofing"? Is there another option? It seems like this would be cumbersome if there are many variables in the .mat file.
Two potential options for how to resolve this are:
  • load your data into a struct array and refer to the variables using struct array indexing.
data = load('mymatfile.mat');
data.f14n
  • Provide some indication in the code that MATLAB should treat that identifier as a variable.
f14n = [];
load mymatfile.mat
"Is there another option?"
You read the load documentation and then load into a structure (which you should be doing every time you use load anyway). Passing one structure is simple.
Jim
Jim el 19 de Jul. de 2017
Thanks again very much. Using a structure is a good easily-workable solution. The second option is also a nice workaround if elegance isn't paramount. Stephen, I wasn't aware that load "should" only load structures. That seems a bit overly constrained. Is there some other reason beyond the one being discussed here that would justify such a constraint?

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Modeling en Centro de ayuda y File Exchange.

Preguntada:

Jim
el 19 de Jul. de 2017

Editada:

el 15 de Oct. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by