MATLAB Answers

# Add a textbox in a subplots inside a loop

8 views (last 30 days)
I want to create a text box for each subplot that are created inside a loop for. But all the text is created in the fist plot and i don't know how to make it for the second one, also i cannot change the titles of any of the plots.
this is my code so far:
clc
clear
z = [0.44,4.7, 7, 8, 17.9, 31, 57];
dim = [.2 .5 .3 .3];
c ={'0.44','4.7', '7', '8','17.9', '31', '57'};
txt = texlabel('H(s) = (5/z*(s+z))/(s^2+37s+232)');
txt2 = texlabel('H(s) = (5*(s+z))/(s^2+37s+232)');
ax1 = subplot(2,1,1);
ax2 = subplot(2,1,2);
for i=1:length(z)
zc=z(i);
%graph1
num=(5)*[1 zc]; % [] valor de los coeficientes del numerador de H(S)
dem =[1 37 232];
h=tf(num, dem);
step(ax1, h)
hold(ax1, 'on')
text(0.8,1,txt,'FontSize',10,'fontname','times')
grid on
%graph2
num2=(5)/(zc)*[1 zc]; % [] valor de los coeficientes del numerador de H(S)
h2=tf(num2, dem);
step(ax2, h2)
hold(ax2, 'on');
annotation('textbox',dim,'String',txt2,'FontSize',10,'fontname','times','FitBoxToText','on');
grid on
end
legend(ax1, c);
legend(ax2, c);
and thats what i'm getting out of it:
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Answers (1)

Jan on 23 Oct 2021
Move the repeated code out of the loop to simplify the code:
z = [0.44, 4.7, 7, 8, 17.9, 31, 57];
dim = [.2 .5 .3 .3];
c = sprintfc('%g', z); % UNDOCUMENTED
txt = texlabel('H(s) = (5/z*(s+z))/(s^2+37s+232)');
txt2 = texlabel('H(s) = (5*(s+z))/(s^2+37s+232)');
ax1 = subplot(2,1,1, ...
'NextPlot', 'add', ... % Same as: hold on
'Grid', 'on');
text(ax1, 0.8, 1, txt, 'FontSize', 10, 'fontname', 'times');
ax2 = subplot(2,1,2 ...
'NextPlot', 'add', ... % Same as: hold on
'Grid', 'on');
annotation('textbox', dim, 'String', txt2, 'FontSize', 10, ...
'fontname', 'times', 'FitBoxToText', 'on');
dem = [1 37 232];
for i = 1:length(z)
zc = z(i);
%graph1
num = 5 * [1 zc]; % [] valor de los coeficientes del numerador de H(S)
h = tf(num, dem);
step(ax1, h)
%graph2
num2 = 5 / zc * [1 zc]; % [] valor de los coeficientes del numerador de H(S)
h2 = tf(num2, dem);
step(ax2, h2)
end
legend(ax1, c);
legend(ax2, c);
Which text should appear where?
Note that text() creates a text in an axes object (created by subplot() here), but annotation writes to a figure.
##### 3 CommentsShowHide 2 older comments
valentina mejia gallon on 25 Oct 2021
Hi Jan,
what I want is that each graphic has a text message.
the first graph must have this text = 'H(s) = (5/z*(s+z))/(s^2+37s+232)'
and the second plot this text ='H(s) = (5*(s+z))/(s^2+37s+232)'
my problem is that the both texts are showing in the first graph.
With the code that you showed me I try to run it but as you can see in the image, it gave me an error. (slide the image to the right to see the error that I got)
Thanks for your help

Sign in to comment.

R2020b

### Community Treasure Hunt

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

Start Hunting!