Generic Variable Names and Cell Arrays

3 ビュー (過去 30 日間)
Sven
Sven 2014 年 11 月 24 日
コメント済み: Image Analyst 2014 年 11 月 29 日
Hello, need to plot different plots, with data delivered in vectors named like:
y_ea, y_eb, c_ea, c_eb, ...
I store the two components of those names before execution in two cellarrays:
response('y','c','k','w')
impulse('ea','eb','em','ew')
thus there are 16 combinations in this case, each one a vector I want to plot. My current solution is using eval but I often read not to use eval but use cellarrays instead. So how do I tackle my problem with cellarrays? Here my current solution with eval:
for r=1:length(response)
for i=1:length(impulse)
str_plot_name = [response{r} '_' impulse{i}]
eval(['plot(' str_plot_name ');'])
end
end
thx for any help.

採用された回答

Guillaume
Guillaume 2014 年 11 月 24 日
The reasons that using eval is frowned upon is that
  1. you don't get automatic syntax check in the body of the eval,
  2. it can't be compiled by the JIT compiler,
  3. more importantly your code depends on variable names over which you have no control. There's no obvious link between the two codes, so if one of the variable is renamed in the other code, it may not be obvious what needs to change in your code.
Thorsten's answer is indeed the approach you should take. If you're stuck with hardcoded variable names, then you have no choice but using eval.
I would use sprintf instead of string concatenation though. I find it easier to read:
str_plot_name = sprintf('%s_%s, response{r}, impulse{i});
eval(sprintf('plot(%s)', str_plot_name));

その他の回答 (1 件)

Thorsten
Thorsten 2014 年 11 月 24 日
編集済み: Thorsten 2014 年 11 月 26 日
You should avoid organizing your data by using 16 different variables. Instead, you can use a 3D matrix M(r,i,:) where r runs from 1 to 4, corresponding to your responses 'y', 'c', 'k' and 'w' and i runs from 1 to 4, corresponding to your impulses 'ea', 'eb', 'em', 'ew'. Then you can use in your two for loops
plot(M(r,i,:))
  1 件のコメント
Image Analyst
Image Analyst 2014 年 11 月 29 日
Sven's comment to Thorsten moved here, instead of being an Answer:
The data comes from another script, thus I can't change how its organized. Would have liked more 3D Matrix-form, but have to handle it this way. So I would still need an answer here.
But I didn't know the one line loop form with a matrix so thx for that already.

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by