필터 지우기
필터 지우기

Help with plotting two lines.

조회 수: 1 (최근 30일)
Matthew Lozancich
Matthew Lozancich 2017년 11월 13일
댓글: Matthew Lozancich 2017년 11월 13일
So I was given a set of x and y coordinates. We were asked to plot the set with a non-connecting points. Then to create a function that generates the best fit line for the list and plot it on the same chart which I did. But it ended up with a bunch of vertical lines connecting the data points and the best fit line together...(
(I've attached a picture)). How do I remove this? Here is my code if you need it for reference:
function cubicfit(x,y)
xp=x;
yp=y;
plot(xp,yp,'.')
xlabel('X data')
ylabel('Y data')
hold on
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A=zeros(41,4);
for i=1:length(x)
A(i,1)=[((x(i))^3)];
end
for i=1:length(x)
A(i,2)=[((x(i))^2)];
end
for i=1:length(x)
A(i,3)=[((x(i))^1)];
end
for i=1:length(x)
A(i,4)=[((x(i))^0)];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
c=(((A')*A)^-1)*((A')*y)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:length(x)
y(i)=((c(1)*(x(i)))^3)+((c(2)*(x(i)))^2)+((c(3)*(x(i))))+(c(4));
plot(x,y,'-')
end

채택된 답변

Walter Roberson
Walter Roberson 2017년 11월 13일
In the sequence
for i=1:length(x)
y(i)=((c(1)*(x(i)))^3)+((c(2)*(x(i)))^2)+((c(3)*(x(i))))+(c(4));
plot(x,y,'-')
end
you are defining one new y value at a time, but you are plotting all the y values each time.
You need to postpone the plot to after the loop.
  댓글 수: 1
Matthew Lozancich
Matthew Lozancich 2017년 11월 13일
Yuppp that was the problem. This literally gets me every time. Once again, thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by