Info
この質問は閉じられています。 編集または回答するには再度開いてください。
Assigning a variable in a function that is available in the function
1 回表示 (過去 30 日間)
古いコメントを表示
I have a function which creates variables (which I want to use in the function only) that are listed in a file that contain the actual variable name and the associated starting/default value. I have tried assign(ws, 'var', val) where 'var' and val come from the file. The problem is these are being assigned to he base ws (regardless if ws = 'base' or 'caller'). I thought I could use evalin but that function needs to know the name of the variable you want to assign it to and that name comes from the file.
3 件のコメント
Sean de Wolski
2014 年 10 月 14 日
That sounds really difficult. Can you provide an actually minimal working example. You should not use or need eval to do this.
回答 (2 件)
Robert Cumming
2014 年 10 月 14 日
Create a sub function which assigns (using assignin) your variables in the caller function where the caller function is the one where you actually want the variables.
0 件のコメント
Matt J
2014 年 10 月 14 日
編集済み: Matt J
2014 年 10 月 14 日
Methods that avoid eval and assignin are preferable (by far) for this kind of thing. You should use load as Sean suggested, but with an output argument
defaults=load('YourFile.mat');
You should also have the user provide a similar structure whose fields are the overrides
override.var1=val1
override.var2=val2;
etc...
Now you just loop through the fields of "defaults" and replace with overrides as needed,
settings=defaults;
fnames=fieldnames(settings);
for i=1:length(fnames)
if isfield(overrides,fnames{i})
settings.(fnames{i})=overrides.(fnames{i});
end
end
The desired data are now all in the fields of the structure "settings". If you strongly prefer them unpacked into separate variables, you could do so with STRUCTVARS ( Download ).
0 件のコメント
この質問は閉じられています。
参考
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!