Plotting data from two matrices on the same plot

Viewed 46

I need to plot data contained in the first 5 rows of two 21*120 matrices with the caveat that the data from one matrix should be plotted as lines and the data from the second - as circles on the same plot.

I'm not sure how to correctly reference x and y when trying to plot a matrix so I circumvented the issue by creating a bunch of vectors:

x = 1:120;
y1 = V(1, :);
y2 = V(2, :);
y3 = V(3, :);
y4 = V(4, :);
y5 = V(5, :);
k1 = K(1, :);
k2 = K(2, :);
k3 = K(3, :);
k4 = K(4, :);
k5 = K(5, :);

% Plot combined figure with forward- and backtracked data
figure
plot(x, y1, 'r', x, y2, 'g', x, y3, 'b', x, y4, 'y', x, y5, 'c',...
     x, k1, 'ro', x, k2, 'go', x, k3,'bo', x, k4, 'yo', x, k5', 'co');

This works but there must be an easier way of doing this, right?

1 Answers

A simple way would be to replace y1, y2, etc. with just the slice notation to take a slice of V. Then you don't need all those unnecessary variables.

plot(x, V(1, :), 'r', x, V(2, :), 'g', ... % and so on

But even better, define a cell array with the color names, and use a loop!

colors = {'r', 'g', 'b', 'y', 'c'};
figure;
hold on;

for ii=1:5
    plot(x, V(ii, :), 'color', colors{ii})
    plot(x, K(ii, :), 'color', colors{ii}, 'marker', 'o')
end

This way is much less tedious if you have many more columns to plot. It's also easy to extend if you have more columns!

nrows = size(V, 1);

colors = jet(nrows);
figure;
hold on;

for ii=1:nrows
    plot(x, V(ii, :), 'color', colors(ii, :))
    plot(x, K(ii, :), 'color', colors(ii, :), 'marker', 'o')
end

jet(n) returns a n x 3 array where each row is a color in the jet colormap.

Related