Dear all:
I try to set a separate file for parameters in a model, and I want to retain their name so later on I can do sensitivity analysis using string comparison to identify the parameter name. So I define my parameters into structures, such as:
param.eps = 6;
param.beta = 0.99;
param.theta = 0.7532;
param.gamma = 0.5;
I want to release the structures into into variables as the following:
eps = 6;
beta = 0.99;
theta = 0.7532;
gamma = 0.5;
Is there an automatic way for doing this? I suspect I can setup the structure contains the name and value separately, and I probably can run a loop to equate the name with the value. But I think there must be a quicker and better way of doing this...
Any comments will be appreciated.
Cheers
Ben

 採用された回答

Jan
Jan 2011 年 8 月 1 日

1 投票

Staying at the structs has some benefits if you use dynamic field names:
param.eps = 6;
param.beta = 0.99;
param.theta = 0.7532;
param.gamma = 0.5;
fields = fieldnames(param);
for i = 1:length(fields)
aField = fields{i};
fprintf('%s = %g\n', aField, param.(aField));
end
If you assign the variable "eps" dynamically, you will overwrite the built-in function with the same name. Such tricks will impede the debugging dramatically!
But if you really have a really good reason to need this really:
function FieldToVar(S)
F = fieldnames(S)
for i = 1:length(F)
aF = F{i};
assignin('caller', aF, S.(aF));
end
This is faster than an equivalent EVAL approach and less dangerous. Nevertheless, I think, this method is worse than using the dynamic field names directly.

その他の回答 (1 件)

Oleg Komarov
Oleg Komarov 2011 年 8 月 1 日

0 投票

Why would you like to do such a thing?
% A method that avoids eval:
fnames = fieldnames(param);
save('param.mat','-struct','param')
load('param.mat')
delete('param.mat') % Or save it in the temp folder

2 件のコメント

Ben Wang
Ben Wang 2011 年 8 月 1 日
Hi Oleg:
I want the parameters to be identified by their names rather than matrix(or vector) index. This would help me alot later on when I do complex sensitivity analysis, so that I can change the value of the parameters by matching the names. (I guess the only benefit is a more intuitive code and less matching errors)
Thanks for replying
Ben
Oleg Komarov
Oleg Komarov 2011 年 8 月 1 日
Why can't you keep the structure. It's there for this reason and allows you to dynamically index the fields.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

タグ

質問済み:

2011 年 8 月 1 日

Community Treasure Hunt

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

Start Hunting!

Translated by