MATLAB: Can’t see the text on a plot, but only for some values

ode45 solutions text

Hey there, I'm trying to put on a text on the max value in a graph of solutions for second ODE. The equations depends on a variable n. In some cases I can see the text on the graphs and in others I can't – depend what is the value of n.
this is my code and my text info, the odefun function gives a solution for this ODE :
x^2*y''+x*y'+(x^2-n^2)=0
[x, Y]= ode45(@odefun, [0.5, 20], [1 1]);
figure;
plot(x,Y);
title('Y as a function of x');
xlabel('x');
ylabel('Y(x)');
max_value=max(Y)
max_x=max_value(1)
max_y=max_value(2)
txt='Max Value';
text(max_x, max_y, txt,'FontSize', 10, 'color', 'red', 'VerticalAlignment', 'top');
end

Best Answer

When I used the Symbolic Math Toolbox to create ‘odefun’, the problem became obvious. You are using the two ‘Y’ values to define the x and y coordinates for your text object.
Try this slight variation:
n = 4.2;
odefun = @(x,Y,n)[Y(2);-1.0./x.^2.*(x.*Y(2)-n.^2+x.^2)];
[x, Y]= ode45(@(x,Y)odefun(x,Y,n), [0.5, 20], [1 1]);
figure;
plot(x,Y);
title('Y as a function of x');
xlabel('x');
ylabel('Y(x)');
[max_value,idx] = max(Y);
max_x=max_value(1);
max_y=max_value(2);
txt='Max Value';
text(x(idx), max_value, txt,'FontSize', 10, 'color', 'red', 'VerticalAlignment', 'top', 'HorizontalAlignment','center')