Reputation: 1
I'm trying to plot the cumulative sum of a series against the infinite sum, and can't get the colors in the legend to match those on the graph. Not really sure what I'm doing wrong here. My code is below:
p = .99;
k = 0:1:1000;
geomSeries = p.^k;
G = sum(geomSeries);
figure;
hold on;
plot(k,G,'r');
h = cumsum(geomSeries);
plot(k,h,'b');
xlim([k(1) k(end)]);
ylim([0 G+10]);
xlabel('Values of k');
ylabel('Cumulative sum');
title('Infinite series of p^k');
legend('Infinite sum','Finite series');
Upvotes: 0
Views: 1375
Reputation: 104504
With legend
calls, you need to make sure all of your plots are there in one function call before you call legend
. As such, combine your plot of the normal geometric series with its cumulative sum together in one function call, and then call legend
accordingly. In addition, k
is a vector while G
is a single number. My guess is that you would like each value of k
to map to the same value of G
, and so you have to make sure that G
is a vector too.
As such, do something like this:
p = .99;
k = 0:1:1000;
geomSeries = p.^k;
%// NEW - Compute all terms first
G = sum(geomSeries);
h = cumsum(geomSeries);
%// NEW - Combine terms into one plot
%// Also make sure `G` has the same number of terms as k
figure;
hold on;
plot(k,G*ones(1,numel(k)),'r',k,h,'b');
xlim([k(1) k(end)]);
ylim([0 G+10]);
xlabel('Values of k');
ylabel('Cumulative sum');
title('Infinite series of p^k');
legend('Infinite sum','Finite series');
This is what I get with your code modified above:
Upvotes: 2