Why do i get the error "inconsistent row/column dimensions" for line a=X\y

4 views (last 30 days)
i=3.5
j=10.0
k=14.5
x=[0.0:0.5:i]'
y=[20.4;17.8;15.5;13.4;11.3;9.2;6.9;5.9]
X=[x ones(x)]
a=X\y
xx=[0.0:0.5:i+0.5]'
yy=a(1)*xx+a(2)
plot(xx,yy)
plot2d(x,y,-1)
x=[i+0.5:0.5:j]'
y=[5.9+0.5;6.1;6.3;6.6;6.9;7.2;7.5;7.8;8.0;8.3;8.5;8.6;8.9;9.6]
X=[x ones(x)]
a=X\y
xx=[i-1:0.5:j+1]'
yy=a(1)*xx+a(2)
plot(xx,yy)
plot2d(x,y,-1)
x=[j+0.5:0.5:k]'
y=[9.6+0.5;10.5;11.4;12.2;13.1;13.8;14.5;15.2;16.0;16.6]
X=[x ones(x)]
a=X\y
xx=[j-1:0.5:k+1]'
yy=a(1)*xx+a(2)
plot(xx,yy)
plot2d(x,y,-1)
  2 Comments
Dyuman Joshi
Dyuman Joshi on 13 Oct 2022
Edited: Dyuman Joshi on 13 Oct 2022
You have defined X incorrectly, ones() requires scaler input and for doing using mldivide (\), both X and y need to have same number of rows.

Sign in to comment.

Answers (1)

dpb
dpb on 13 Oct 2022
This time I formatted your code for you; in future use the "CODE" button to do so (or select code and use CTRL-E).
Please add the trailing semicolons so don't overwhelm output screen with echo of every line.
The above code doesn't get that far even
i=3.5;
j=10.0;
k=14.5;
x=[0.0:0.5:i].';
y=[20.4;17.8;15.5;13.4;11.3;9.2;6.9;5.9];
X=[x ones(x)];
a=X\y;
You were probably looking for
X=[x ones(size(x))];
instead.
Then
p=X\y
plot(x,y,'*-')
hold on
yhat=polyval(p,x);
plot(x,yhat,'r-')
works as intended.
However, NB that
b=polyfit(x,y,1)
produces the same result with less user code.
And also note you can evaluate polynomials with polyval or polyconf
  2 Comments
dpb
dpb on 13 Oct 2022
Glad to help...
If this solved your problem, please "ACCEPT" the Answer if for no other reason than to let others know there has been a resolution...

Sign in to comment.

Categories

Find more on Data Distribution Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!