- 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
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sven
el 24 de Nov. de 2014
Comentada: Image Analyst
el 29 de Nov. de 2014
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 comentarios
Respuesta aceptada
Guillaume
el 24 de Nov. de 2014
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 comentarios
Más respuestas (1)
Thorsten
el 24 de Nov. de 2014
Editada: Thorsten
el 26 de Nov. de 2014
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 comentario
Image Analyst
el 29 de Nov. de 2014
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.
Ver también
Categorías
Más información sobre Data Type Identification en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!