matlab: is there a way to import/promote variables from a structure to the current workspace?

廉价感情. 提交于 2019-12-11 01:27:06

问题


function y = myfunc(param)
C = param.C;
L = param.L;
Kp = param.Kp;
Ki = param.Ki;
...

Is there a way to generalize the above code? I know how to generalize the structure access using fieldnames() and getfield(), but not how to set variables without calling eval() (which is evil).

for n = fieldnames(param)'
  name = n{1};
  value = param.(name);
  do_something_with(name,value);   % ????

回答1:


never mind, I figured it out; this helper function works:

function vars_pull(s)
    for n = fieldnames(s)'
        name = n{1};
        value = s.(name);
        assignin('caller',name,value);
    end



回答2:


The only way to create a variable whose name is determined at run-time is to use a function like eval, evalin, feval, or assignin. (assignin is the least evil choice BTW, at least you don't need to convert your value to a string and back.)

However, I question why you want to do that, why not just access the values through the input structure as you need them. If you want to save typing (speaking from experience, as I am extremely lazy), I usually name my input parameter structure something short, like p. The throughout my code I just access the fields directly, (e.g. p.Kp, and after a while I don't even see the p. anymore.) This also makes it easy to pass the structure into subfunctions as needed.




回答3:


You can use the excellent submission at FileExchange:

V2STRUCT - Pack & Unpack variables to & from structures with enhanced functionality




回答4:


Here's a workaround: save the structure to a .mat file using the '-struct' option, and then immediately reload it. Here's an example for struct variable X:

save('deleteme.mat','-struct','X');
load('deleteme.mat');
delete('deleteme.mat');

It's kludgey, but actually pretty fast, at least with an SSD.



来源:https://stackoverflow.com/questions/9669635/matlab-is-there-a-way-to-import-promote-variables-from-a-structure-to-the-curre

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