This is a least-squares problem, but I cannot get the "best fit line" to generate. I can plot markers however. Specifying '-', 'LineWidth' and others do not work. What am I doing wrong here? Software is R2015a
WS = [1912 82.2; 1920 73.6; 1924 72.4; 1928 71; 1932 66.8; 1936 65.9;
1948 66.3; 1952 68.8; 1956 62; 1960 61.2; 1964 59.5; 1968 60;
1972 58.59; 1976 55.65; 1980 54.79; 1984 55.92; 1988 54.93; 1992 54.65;
1996 54.50; 2000 53.83; 2004 53.84; 2008 53.12; 2012 53.00];
A = zeros(23,2); %shapes matrix dimensions for dataset
A(1:23,1) = ones; %design matrix ones
A(1:23,2) = WS(1:23,1); %fills design matrix with the independent variables
b = WS(1:23,2); %allocates parameters from dataset
x = (inv(A' * A)) * (A') * b;
for k = 1:23
y = (x(1,1) + x(2,1) * A(k,2));
plot(A(k,2),y)
hold on;
end

 採用された回答

dpb
dpb 2015 年 11 月 9 日
編集済み: dpb 2015 年 11 月 10 日

0 投票

Wrong way to go about it...using the explicit design matrix and direct inversion is poor numerically...instead
plot(WS(:,1), WS(:,2)) % plot raw data
coef=polyfit(WS(:,1), WS(:,2),1); % Linear LS polynomial
yHat=polyval(coef,WS(:,1)); % compute fitted values
hold on
plot(WS(:,1), yHat,'r-') % add predicted values
The reason your plot only produces markers is you're plotting a single point at a time in the loop instead of drawing the line with the vectors.
See
doc polyfit % and friends
or for more general models than polynomial,
doc \ % or "mldivide"
for the generalized matrix "left divide" implemented in Matlab that is much more robust numerically.

3 件のコメント

K G
K G 2015 年 11 月 16 日
Thank you for this. Unfortunately, after inquiring with my professor, we can't use the polyfit function. This is a linear algebra course and the lab component is designed to be marked according to what or how we learn MatLab. I know my code is cumbersome, but do you have any other ideas?
dpb
dpb 2015 年 11 月 16 日
Well, the code "works" in solving but I'd iterate the caveat re: the numerics in general. Perhaps your course will cover that later.
I would, however, even if using the explicit formulation, modify the naming convention you've chosen to return the solution for the coefficients in a variable that has some relation to what it is.
The problem you're having with the plotting is as outlined; you're plotting each point individually; even if you use the technique you have to solve for the coefficients you can still compute the results with a vector expression then plot the results without a loop.
As it is class work, I'll let the hint suffice for now... :)
Walter Roberson
Walter Roberson 2015 年 11 月 16 日
Replace your
y = (x(1,1) + x(2,1) * A(k,2));
with
y(k) = (x(1,1) + x(2,1) * A(k,2));
and delete the plot() you have there. Then after the loop,
plot(A(2,:), y)

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

その他の回答 (0 件)

カテゴリ

質問済み:

K G
2015 年 11 月 9 日

コメント済み:

2015 年 11 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by