MATLAB: Legend color is not match

legend colour unmatched

hi,guys,
my code is to plot 3 sets of data,in blue ,red and green respectively, however, the legend is not match for the third one (it is the same with the 2rd one), can anyone help me?
————————————————————————————————–
clear
filename = '1.log';
set = 768;
fid = fopen(filename,'r');
[num1,num2] = textread(filename,'%d%d');
lines = get_lines(fid);
length = 1:1:lines;
title('haha');
xlabel('hehe');
ylabel('heihei');
plot(length,num1,'-b*',length,set,'-r',length,num2,'-go');
hleg = legalpha('1','2','3');
fclose('all');
the results:

Best Answer

Huh, there's a lot to comment.
1. To your question: Let me copy the important lines:
set = 768;
length = 1:1:lines;
plot(length,num1,'-b*',length,set,'-r',length,num2,'-go');
"set" has only one value, length has multiple values. When you do something like
plot(1:3,1,'-r'), legend show
you'll create 3 plots with equal style. The only thing which puzzles me is that you can see the red line. I expected no red line to be visible as each plot has only one point and there's no line to print.
What you can do is to plot it like this:
plot([1 lines],[set set],'-r')
Then, please see some additional comments:
2. "length" is a built-in function. Don't use this as variable name as this might cause odd and unexpected behavior of your program.
3. If you create an array with an increment of 1, you don't need to specify this increment. Just myarray=1:lines is fine (I don't want to use "length" as variable name again).
4. I don't know this get_lines function, but as you have already read the content of the file, a simple
lines=length(num1);
will do the same job. As long as you didn't create a variable called length ;-)
5. Close the file soon as possible (here, right after the textread) and just specify the file identifier.
fclose(fid);
If you work with multiple files, a general fclose('all') might cause errors which are tricky to find.
Some of these remarks might sound pedantic but learning a good programming style from the beginning will help you a lot later.