How to plot with lines in a for loop and use legends for each line?

Hello, I'm having trouble using the plot function to plot some values from my array. The problem is, it only shows points, but no lines connected between them.
Here is what my cell array looks like:
matrix{1} = 0.0274 0.0268 0.0275
matrix{2} = 0.0130 0.0128 0.0124
matrix{3} = 0.0111 0.0108 0.0113
matrix{4} = 0.0110 0.0107 0.0107
matrix{5} = 0.0109 0.0107 0.0107
matrix{6} = 0.0109 0.0107 0.0107
matrix{7} = 0.0109 0.0107 0.0107
matrix{8} = 0.0109 0.0107 0.0107
Using the following code produces only points but no lines.
for i = 1:8
for j= 1:3
plot(i, matrix{1}(1, j), '*');
hold on;
end
end
What am I doing wrong?
Also, how can I associate the lines (if working) with a legend?
Thanks!

 Accepted Answer

There is no reason to use cell arrays for this code, and it actually causes the problem that you are experiencing. A very good data concept is to use the simplest array possible, unless a more complicated array is the only choice. In this case a simple numeric array holds all of that data quite nicely, so there is no need to use a cell array.
M = [0.0274 0.0268 0.0275;...
0.0130 0.0128 0.0124;...
0.0111 0.0108 0.0113;...
0.0110 0.0107 0.0107;...
0.0109 0.0107 0.0107;...
0.0109 0.0107 0.0107;...
0.0109 0.0107 0.0107;...
0.0109 0.0107 0.0107]
plot(M,'-*')
legend({'first','second','third'})
creates this:
Summary: do not make data more complicate than it needs to be, it only makes the code more complicated!
PS: here is an easy way to convert that cell array into a simple numeric matrix:
M = vertcat(matrix{:});

More Answers (0)

Products

Tags

Asked:

on 28 Oct 2015

Commented:

on 28 Oct 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!