assignin('caller',…) within a function in Matlab

大兔子大兔子 提交于 2019-12-08 02:43:13

问题


I created this very useful bit of code to assign variables dynamically from a struct :

function getParam(param)
% this function extracts the fields of structure param and assigns them
% to variables of corresponding names in the caller workspace
allFieldsParam = fieldnames(param);
for iField = 1:length(allFieldsParam)
  assignin('caller',allFieldsParam{iField},param.(allFieldsParam{iField}));
end

The problem is that when I call getParam within a function, sometimes it works and sometimes it returns an error of the form :

??? Error using ==> assignin
Attempt to add "blocksizes" to a static workspace.
 See MATLAB Programming, Restrictions on Assigning to Variables
 for details.

    Error in ==> getParam at 7
      assignin('caller',allFieldsParam{iField},param.(allFieldsParam{iField}));

    Error in ==> classif_nmf_db at 15
    getParam(param);

Anyone has a clue how I can fix this ?

Regards AL


回答1:


This is to enforce a good programming practice in MATLAB.

The document you are referred to is located here: Nested functions: Restrictions on Assigning to Variables

The scoping rules for nested, and in some cases anonymous, functions require that all variables used within the function be present in the text of the code. Adding variables to the workspace of this type of function at run time is not allowed.

MATLAB issues an error if you attempt to dynamically add a variable to the workspace of an anonymous function, a nested function, or a function that contains a nested function. ...

Loren also has a blog entry about it.


UPDATE

Have a look on this File Exchange submission: Pack & Unpack variables to & from structures with enhanced functionality (v2struct).



来源:https://stackoverflow.com/questions/8270904/assignincaller-within-a-function-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!