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 件のコメント

Mikolaj Malinski
Mikolaj Malinski 2022 年 10 月 7 日
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
Star Strider
Star Strider 2022 年 10 月 7 日
The first option.
I don’t know of any other ways to use it.
Mikolaj Malinski
Mikolaj Malinski 2022 年 10 月 7 日
I used it as you suggested and it worked. Thank You
Star Strider
Star Strider 2022 年 10 月 7 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangePolynomials についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by