Prashant Kumar answered .
2025-08-23 19:37:31
First you have to forget about eval. There are very few things that can't be done without it (like swapping variables within different workspaces) but this is definitely not it.
eval is prone to errors, complicates readability, hard to debug, overpopulates the workspace, makes project management unfeasible.
I will answer directly your questions, but your issue is more broad and it concerns more project management rather than how to do it in MATLAB.
Question 1
in = {1:10, 11:20, '.',3:4,2:3,'*'};
plot(in{:})
Question 2
str = {'A','B'};
legend(str{:})
What I want to show here is one simple concept. plot and legend have varargin behaviour. They can accept a variable amount of inputs, the trick is to throw those inputs sequentially by "unpacking" the cell array (try to run in{:} and see what happens).
Having shown you one of the methods I would not recomend to follow it blindly. For instance, you "subplot" 3 series, sk_ratio, linear and quadratic fit, but the depth is the same. I would go for a double loop, one for each different group of results and one across the 3 series.
Project management
Obviously you cannot simply import all of your data in a cell array and throw results in a casual way, or hardcode everything as I did to simplify the example.
However, you can use cell arrays in a smarter way or you could use structure which have the benefit of keeping names for the fields (making it easier to remember what corresponds to what).
When I code for myself I use cell arrays and I use columns to separate groups of results and rows to store each specific result. An example:
{sk_ratio01, sk_ratio02;
fitco_1_01, fitco_1_02;
fitco_2_01, fitco_2_02;
'Co-60' , 'MV 4';
'*' , '+'}
where the names for the data are there to ease understanding but in reality I would not create sk_ratio01,...0n but just assign the data to the right position in the cell.
If I have to code for others as well I would use a structure:
s.('sk_ratio01') = struct('data',data,'fit1',fit1,'fit2',fit2,'marker','*','lbl','Co-60');
s.('sk_ratio02') = struct('data',data,'fit1',fit1,'fit2',fit2,'marker','+','lbl','MV 4');
etc..
Summary
To summarize my suggestion: managing correctly your data is the first thing you should aim at. There are different ways of doing it (and eval is not one of them) which involve trade-off between clarity, ease of use and flexibility of the solution.
Both methods I've shown you above (cell arrays and structures) could be implemented programmatically.
EDIT to comment
eval(['spectrum' spectrumname '.energy=' spectrumname])
could be rewritten with dynamic field indexing:
spectrum.(['spn' spectrumname]).energy = spectrumname;
Note that a fieldname cannot start with a number (same rule as for variables applies).
Not satisfied with the answer ?? ASK NOW