Error when trying to plot a polynomial with data.

I have written a code to determine the equation of a line from some data. I need the slope and y-intercept which I have found without a problem but I would also like to plot the polynomial over the data but it keeps giving me an error regarding the vestor sizes not matching.
This is my code
t = [10; 20; 30; 40; 50; 60] ; %time in units of min
Ca = [2.45; 1.74; 1.23; 0.88; 0.62; 0.44] ; %concentration of bromine in ppm
%Need to determine the change in time and concentration over the course of
%the study
dCa = [Ca(2) - Ca(1); Ca(3) - Ca(2); Ca(4) - Ca(3); Ca(5) - Ca(4);...
Ca(6) - Ca(5)] ;
dt = [t(2) - t(1); t(3) - t(2); t(4) - t(3); t(5) - t(4); t(6) - t(5)] ;
%Need to divide the change in concentration by the change in time then take
%the natural logarith of -dCa/dt to find the y coordinates for our plot
diff = dCa./dt ;
y = log(-diff) ;
%Now take the natural logarith of the concentration to determine the x
%values for our plot
x = log(Ca) ;
%Now we can plot the data but since we need to hte same number of data
%points we will only use data points 2-6 for ln(Ca)
plot(x(2:6),y,'bd')
xlabel('ln(Ca)') ;
ylabel('ln(-dCa.dt)') ;
hold on ;
%Use polyfit to determine the equation of the line that best fits our data
%but need to use the same number of data points so we will only use the 2-6
%elements of the ln(Ca)
p = polyfit(x(2:6),y,1) ;
%Print the results of the polynomial
fprintf(['The genrated equation for the line has a slope of m = %4.4f ' ...
'and a y-intercept of b = %4.4f\n'],p(1),p(2)) ;
%Now that we have the equation of the line we will plot it over the data
%points
plot(p,x(2:6),y) ;
legend('Location','NorthWest') ;
And this is the error it keeps giving me
Error using plot
Vectors must be the same length.
Error in HW5 (line 48)
plot(p,x(2:6),y) ;

 채택된 답변

Star Strider
Star Strider 2022년 10월 6일

0 개 추천

Use the polyval function.

댓글 수: 4

Do you mean to use it with my already generated p equation in the following way:
y1 = polyval(p,x)
plot(x,y1,'r-')
or did you have a differnet method in mind
The first option.
I don’t know of any other ways to use it.
I used it as you suggested and it worked. Thank You
As always, my pleasure!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Polynomials에 대해 자세히 알아보기

질문:

2022년 10월 6일

댓글:

2022년 10월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by