How to dynamically change name of table?
Show older comments
This code below is just a very simple example of some analysis I am doing with my experimental results.
I am running 5 cycles of an experiment, results come out in a long txt file, I want to plot everything with a different color based on cycle number. So I am creating sub-tables from the main table based on the parameter of interest. This simple code works parfectly. However, it's fine because it is only 5 runs. What if it was 100?
Is there a more efficient way to assign table names dynamically? I am new with Matlab and I am using my real life needs to practice and learn.
Thank you!
T=readtable("Output-C1_Cu.txt","NumHeaderLines",2);
NT1=T(T.Var2==1,:);
NT2=T(T.Var2==2,:);
NT3=T(T.Var2==3,:);
NT4=T(T.Var2==4,:);
NT5=T(T.Var2==5,:);
plot(NT1,"Var4","Var6",LineWidth=1.5, Color=[0 0.4470 0.7410])
hold on
plot(NT2,"Var4","Var6",LineWidth=1.5, Color=[0.8500 0.3250 0.0980])
hold on
plot(NT3,"Var4","Var6",LineWidth=1.5, Color=[0.9290 0.6940 0.1250])
hold on
plot(NT4,"Var4","Var6",LineWidth=1.5, Color=[0.4940 0.1840 0.5560])
hold on
plot(NT5,"Var4","Var6",LineWidth=1.5, Color=[0.4660 0.6740 0.1880])
hold off
xlim([0,1.5])
xlabel('V cell (V)','FontWeight','bold')
ylabel("dQ/dV cell (mAh/V)","FontWeight","bold")
title('Treated Cu - OG Si')
legend({'Cycle 1','Cycle 2','Cycle 3','Cycle 4','Cycle 5',}, ...
'Location','southeast')
2 Comments
"Is there a more efficient way to assign table names dynamically? "
No, there is not. Every way is slow, inefficient, complex, and pointlessly obfuscates code:
MATLAB is designed around arrays and indexing. Indexing is exactly how you would handle "What if it was 100?", because indexing trivially expands to any size (hint: try using a loop). Indexing is exactly how experienced MATLAB users would do it, or by using the inbuilt tools for processing groups of data:
https://www.mathworks.com/help/matlab/matlab_prog/grouped-calculations-in-tables-and-timetables.html
Your approach of copy-pasting lots of code or dynamically naming variables ... is best avoided.
"I am new with Matlab and I am using my real life needs to practice and learn."
Then forget about dynamic variable names. That is a path you really don't want to go down:
Marina
on 10 Apr 2024
Accepted Answer
More Answers (0)
Categories
Find more on Tables in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

