I am solving a pde that depends on x and t and would like to show the solution over all x for a few values of t. I am trying to write code that will automatically generate a legend for this plot. For example, if I am plotting the solution at t = 0, 1, 5, and 9, I want the legend to show "t=0", "t=1", and so on.
Let's say my solution is held in matrix u. My times are held in vector t. The index of the times I am sampling would be in vector tsampled. Note this is not the same as the time I want on the plot. If I take the time at index 6 of vector t, this value is not 6, but could be anything.
I am currently attempting to do this by:
tlen = max(size(t));
tsampled = [2, floor(tlen/5), floor(2*tlen/5), floor(3*tlen/5), floor(4*tlen/5), floor(tlen)];
t(tsampled)
legnd = {'', '', '', '', '', ''};
hold on
for i = 1:1:size(tsampled)
plot(x,u(tsampled(i),:))
legnd(i) = sprintf('t = %0.2f s \n', t(tsampled(i)));
end
title('my PDE solution');
legend(legnd, 0);
xlabel('x')
ylabel('u')
hold off
But this is producing the error "Conversion to cell from char is not possible."
When I instead try using the line:
legend (sprintf('t = %0.2f s \n', t(tsampled)))
I get the correct "strings" on the graph, but they are formatted like this:
I would like this to show "t=10.20 s" next to a blue line, "t = 91.84 s" next to an orange line, and so on. How do I get the result I want?