0

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: enter image description here

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?

farid99
  • 712
  • 2
  • 7
  • 25
  • Could you show us how you defined `t` and `u`? – jadhachem Apr 25 '15 at 21:05
  • u is defined as the result of a "pdepe" call, and t is simply: t = linspace(0, 500, 5000); – farid99 Apr 25 '15 at 21:08
  • Your problem might come from using `size` instead of `length` in the line `for i=1:1:size(tsampled)`. Try `length` instead. I can't tell exactly though because I could not reproduce your problem. – jadhachem Apr 25 '15 at 21:09
  • My problem is in the generation of a legend, not so much the data itself. Basically, how do I generate the legend to do what I want it to do. As far as the data goes, it does work. – farid99 Apr 25 '15 at 21:12
  • I understand. `tsampled` is a vector, and so `size(tsampled)` returns `[1 n]` for some integer `n`. This will cause your loop to execute only once. I suspect that you're plotting all data in one shot. And the line `legend(sprintf('t = %0.2f s \n', t(tsampled)))` is producing one big string with all the "t=" lines in it. – jadhachem Apr 25 '15 at 21:16

1 Answers1

3

Because you predefined legnd as a cell array, you need to use {} instead of () to get the correct index. Try:

legnd{i} = sprintf('t = %0.2f s \n', t(tsampled(i)));
chepyle
  • 976
  • 1
  • 9
  • 16