如何在任何matlab函数中将char值作为double值传递我提供了与char同名的双变量(请参阅详细信息)?

时间:2017-11-21 18:32:28

标签: matlab

%%我想将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    

1 个答案:

答案 0 :(得分:2)

您必须使用eval来评估变量名称,为您提供变量包含的数据向量:

histogram(eval(var_name{1}));

但是,我猜你有更好的方法可以解决你的问题,因为using dynamically named variables is general not good practice

根据您更新的示例,您可以使用structuresdynamic 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