Matlab函数中的assignin('caller',...) [英] assignin('caller',...) within a function in Matlab

查看:616
本文介绍了Matlab函数中的assignin('caller',...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这段非常有用的代码,用于从struct动态分配变量:

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

问题是,当我在函数中调用getParam时,有时它可以工作,并且有时会返回以下形式的错误:

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 ?

问候 AL

推荐答案

这是为了在MATLAB中实施良好的编程习惯.

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会发出错误 匿名函数,嵌套函数或 包含嵌套函数的函数. ...

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还具有博客条目关于它.

Loren also has a blog entry about it.

更新

查看此文件交换提交: 打包将变量解压到&来自具有增强功能(v2struct)的结构.

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

这篇关于Matlab函数中的assignin('caller',...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆