- you don't get automatic syntax check in the body of the eval,
- it can't be compiled by the JIT compiler,
- 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.
Generic Variable Names and Cell Arrays
3 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Guillaume
2014-11-24
The reasons that using eval is frowned upon is that
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));
0 个评论
更多回答(1 个)
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
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 Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!