Generic Variable Names and Cell Arrays

조회 수: 4 (최근 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 CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by