I do not understand why I am getting this error
1 回表示 (過去 30 日間)
古いコメントを表示
The vectors below are loaded through two separate text files, hence the lack of commas among the vector elements. To the vectors below, I apply the following code and I get the following error:
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in Problem5_18 (line 27) sumxy(i)=sumxy+(x(i)*y(i));
I even tried
sumxy(i)=sumxy+(x(i).*y(i));
to no avail. I am missing smth obvious and would appreciate the extra set of eyes.
******************************************Code
function [m,b] = Problem5_18(x,y)
%Problem5_18 Linear Least-Squares Fit.
%This function calculates slope m and intercept b of the least-squares line
%that best fits an input dataset.
narginchk(2,2);
if nargout<2
m='Make sure that you ask for both outputs!';
warning(m);
end
if length(x)~=length(y)
n='Check your inputs; input arrays must be of the same length!';
error(n);
end
sumxy=zeros(length(x));
sumx=zeros(length(x));
sumy=zeros(length(x));
sumx2=zeros(length(x));
for i=1:length(x)
sumxy(i)=sumxy+(x(i)*y(i));
sumx(i)=sumx+x(i);
sumy(i)=sumy+y(i);
sumx2(i)=sumx2+(x(i)^2);
end
ybar=sumy/length(x);
xbar=sumx/length(x);
m=(sumxy-(sumx*ybar))/(sumx2-(sumx*xbar));
b=ybar-(m*xbar);
*************************************************Datasets
x=[ -4.91 -3.84 -2.41 -2.62 -3.78 -0.52 -1.83 -2.01 0.28 1.08 -0.94 0.59 0.69 3.04 1.01 3.60 4.53 5.13 4.43 4.12]
y=[ -8.18 -7.49 -7.11 -6.15 -5.62 -3.30 -2.05 -2.83 -1.16 0.52 0.21 1.73 3.96 4.26 5.75 6.67 7.70 7.31 9.05 10.95]
0 件のコメント
採用された回答
the cyclist
2014 年 10 月 19 日
I fixed several issues. The biggest one is that
zeros(N)
will create and NxN array, not an Nx1 array. So, I assume you wanted
sumxy=zeros(length(x),1);
etc.
Next, I changed
sumxy(i)=sumxy+(x(i).*y(i));
to
sumxy(i)=sumxy(i)+(x(i).*y(i));
because I assume that's what you intended.
Finally, in the last two lines, I added more element-wise operations.
In the end, it runs. I have no idea if it does what you intend.
function [m,b] = Problem5_18(x,y)
%Problem5_18 Linear Least-Squares Fit.
%This function calculates slope m and intercept b of the least-squares line
%that best fits an input dataset.
narginchk(2,2);
if nargout<2
m='Make sure that you ask for both outputs!';
warning(m);
end
if length(x)~=length(y)
n='Check your inputs; input arrays must be of the same length!';
error(n);
end
sumxy=zeros(length(x),1);
sumx=zeros(length(x),1);
sumy=zeros(length(x),1);
sumx2=zeros(length(x),1);
for i=1:length(x)
sumxy(i)=sumxy(i)+(x(i)*y(i));
sumx(i)=sumx(i)+x(i);
sumy(i)=sumy(i)+y(i);
sumx2(i)=sumx2(i)+(x(i)^2);
end
ybar=sumy/length(x);
xbar=sumx/length(x);
m=(sumxy-(sumx.*ybar))./(sumx2-(sumx.*xbar));
b=ybar-(m.*xbar);
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Function Creation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!