MATLAB Legend Color and semilogy() Plotting Problems

조회 수: 8 (최근 30일)
Kody
Kody 2013년 10월 27일
답변: Walter Roberson 2013년 10월 27일
I am new to MATLAB and am just recently building a simple program. Everything seems to work fine except my legend is only showing the color red for all 5 of my semilogy() plots and I am getting unnecessary line from my plots to the x intervals. I realize my code isn't very efficient. It is pretty much the same code looped 5 times except with different g values. How can I fix my legend colors to be different and to get rid of the lines in my graph running to the x intervals?
close all; clear; clc;
g1 = 0.5; g2 = 0.618; g3 = 0.7; g4 = 0.8; g5 = 0.9;
f = @ (x) 2*sin(x) - (x.^2/10);
it = 20;
tol = 0.0001;
xl = 0;
xu = 4;
xlabel('Iterations');
ylabel('Bracket Interval Size Pending G Value');
bs = zeros(20,1);
hold on;
for i = 1:it
r1 = g1 * (xu - xl);
deltax1 = 0.01 * r1;
fl1 = f(xl + r1 - deltax1);
fu1 = f(xl + r1 + deltax1);
if fl1 > fu1
xu = xl + r1;
else
xl = xl + r1;
end
bs(i) = xu - xl;
semilogy(bs, 'r');
if abs((fl1 - xl) / xl) < tol
break
end
end
xl = 0;
xu = 4;
for i = 1:it
r2 = g2 * (xu - xl);
deltax2 = 0.01 * r2;
fl2 = f(xl + r2 - deltax2);
fu2 = f(xl + r2 + deltax2);
if fl2 > fu2
xu = xl + r2;
else
xl = xl + r2;
end
bs(i) = xu - xl;
semilogy(bs, 'b');
if abs((fl2 - xl) / xl) < tol
break
end
end
xl = 0;
xu = 4;
for i = 1:it
r3 = g3 * (xu - xl);
deltax3 = 0.01 * r3;
fl3 = f(xl + r3 - deltax3);
fu3 = f(xl + r3 + deltax3);
if fl3 > fu3
xu = xl + r3;
else
xl = xl + r3;
end
bs(i) = xu - xl;
semilogy(bs, 'k');
if abs((fl3 - xl) / xl) < tol
break
end
end
xl = 0;
xu = 4;
for i = 1:it
r4 = g4 * (xu - xl);
deltax4 = 0.01 * r4;
fl4 = f(xl + r4 - deltax4);
fu4 = f(xl + r4 + deltax4);
if fl4 > fu4
xu = xl + r4;
else
xl = xl + r4;
end
bs(i) = xu - xl;
semilogy(bs, 'g');
if abs((fl4 - xl) / xl) < tol
break
end
end
xl = 0;
xu = 4;
for i = 1:it
r5 = g5 * (xu - xl);
deltax5 = 0.01 * r5;
fl5 = f(xl + r5 - deltax5);
fu5 = f(xl + r5 + deltax5);
if fl5 > fu5
xu = xl + r5;
else
xl = xl + r5;
end
bs(i) = xu - xl;
semilogy(bs, 'y');
if abs((fl5 - xl) / xl) < tol
break
end
end
xlabel('Iterations');
ylabel('Bracket Interval Size Pending G Value');
legend('g = 0.5', 'g = 0.618', 'g = 0.7', 'g = 0.8', 'g = 0.9');
hold off;

채택된 답변

Walter Roberson
Walter Roberson 2013년 10월 27일
Move your semilogy() calls out of the "for" loops they are in, to after the end of each "for i" loop -- after, that is, you have calculated each entire "bs" vector.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by