%%我想将char(此处为var_name {1})的值传递为直方图函数中double(此处为x)的值。我怎样才能做到这一点?
% var_name could be much bigger
h={'h1','h2'}
var_name ={'x','y'}
time_step=100;
for i =1:time_step
x=%code that extract x from some data file %
y= %get y from some other file (actually using find command)
%the time loop will overwrite the x and y values
` for k=1:length(var_name)
%figure h
h{k}=histogram(var_name{k}) % I have been suggested to avoid eval %
%lot of procees to do here for every variable say x y than save the
%saveas(h{k},sprintf(...))
end
end
答案 0 :(得分:2)
您必须使用eval
来评估变量名称,为您提供变量包含的数据向量:
histogram(eval(var_name{1}));
但是,我猜你有更好的方法可以解决你的问题,因为using dynamically named variables is general not good practice。
根据您更新的示例,您可以使用structures和dynamic field names的一种非eval
方式:
for i = 1:time_step
data.(var_name{1}) = % code that extract xs from some data file
data.(var_name{2}) = % get y from some other file (actually using find command)
for k = 1:length(var_name)
h{k} = histogram(data.(var_name{k}));
...
end
...
end