how to draw line between points in Matlab
조회 수: 6 (최근 30일)
이전 댓글 표시
I have to plot a graph showing results in a for loop, the problem is that I only get points instead of a proper graph: here is my code:
%this program plots the number of iterations versus the
% errors in a bisection methode which is used to find he zero of a function.
clc
a=0;
b=2;
E0=[]
f=@(x)exp(-exp(-x))-x %the nonlinear function
for i=3:10
e=10^-i
n=ceil(log(b-a)-log(e)/log(2))
hold on
axis([10^-10 10^-3 0 12])
grid on
plot(e,n,'.')
for i=1:n
c=(a+b)/2;
if f(c)*f(a)<0
b=c;
else
a=c;
end
end
end
your help is Appreciated! Thank you
댓글 수: 1
채택된 답변
Niels
2017년 1월 9일
편집: Niels
2017년 1월 9일
if you want lines between the points you have to save the data in vectors and plot the vectors, not single points
i changed some lines in your codes, take a look
a=0;
b=2;
E0=[];
% since you know what size e and n will have you can define them here alrdy
[e,n]=deal(zeros(8,1))
f=@(x)exp(-exp(-x))-x; %the nonlinear function
for i=3:10
% index starts at 1
e(i-2)=10^-i;
n(i-2)=ceil(log(b-a)-log(e(i-2))/log(2));
hold on
axis([10^-10 10^-3 0 12])
grid on
% points can still be plottet
plot(e(i-2),n(i-2),'.')
% why i again, you used i inprevious loop
% dont use same variable for index of a loop in a loop
for j=1:n
c=(a+b)/2;
if f(c)*f(a)<0
b=c;
else
a=c;
end
end
end
% plot lines between the points
plot(e,n)
you should test this comman with other examples like
x=linspace(0,2*pi,100);
plot(x,sin(x))
댓글 수: 2
Niels
2017년 1월 9일
편집: Niels
2017년 1월 9일
If you look at your code e and n should be underlined in red. Read what matlab displays. It should be something like e and n changes size every ... so to start with e is not defined. Then its a 1x1 vector. Next iteration its 1x2 etc same for n. This slows down matlab but in your case its not rly worth mentioning. In general if the size is know you better define the variable. Deal(zeros...) sets the previous mentioned variables to a 8x1 vector, each entry 0
추가 답변 (1개)
Image Analyst
2017년 1월 9일
You didn't completely specify the line style. You can specify color, line style, and marker. For example to do a red solid line of width 2, with spot shaped markers of size 15:
plot(e, n, 'r.-', 'LineWidth', 2, 'MarkerSize', 15);
참고 항목
카테고리
Help Center 및 File Exchange에서 Line Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!