How to write a For loop for the last characters vector names

I have the following variables that I want to plot:
t=1:1:20
P_eA
P_eZ
C_eA
C_eZ
I can make a subplot by writing
figure(1)
subplot(2,1,1)
plot(t, P_eA)
subplot(2,1,2)
plot(t, C_eA)
figure(2)
subplot(2,1,1)
plot(t , P_eZ)
subplot(2,1,2)
plot(t, C_eZ)
However, I'm wondering if there is a way to write a for loop where I can loop over the last characters of each vector. What I am thinking of is something like
char = char('eA','eZ');
for i=1:2
figure(i)
subplot(2,1,1)
plot(t, P_{char(i,:)})
subplot(2,1,2)
plot(t, C_{char(i,:)})
end
end

 Accepted Answer

Example: You could also use a table () for this. https://www.mathworks.com/help/matlab/matlab_prog/generate-field-names-from-variables.html. Note: Naming a variable char is a terrible idea!!
clear all
t=1:1:20
P.eA = rand(1,20)
P.eZ = rand(1,20)
C.eA = rand(1,20)
C.eZ = rand(1,20)
P_names =fieldnames(P)
C_names =fieldnames(C)
for k = 1:numel(P_names)
figure(k)
subplot(2,1,1)
plot(t, P.(P_names{k}))
subplot(2,1,2)
plot(t, C.(C_names{k}))
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!