Keep getting this polyfit error and don't know how to fix, error using polyfit "the first two inputs must have the name number of elements"

3 views (last 30 days)
JobSector = app.JobSectorsInSolarDropDown.Value;
switch JobSector
case 'Installation & Project Development'
hold(app.UIAxes, "off")
plot(app.UIAxes,app.xyears,app.yipd,'ob')
%ployfit- provies coefficients for the regression
%equation
IPDcoef= polyfit(app.xyears,app.yipd,1);
%IPDcoef= [m,b]
m= IPDcoef(1);
b= IPDcoef(2);
%function handle
IPDFUNC= @(x) m*x+b;
%regression equation
hold(app.UIAxes,"on")
fplot(app.UIAxes,IPDFUNC,[min(app.xyears),max(app.xyears)],'-r')
end
%error i get in command window
%Error using polyfit (line 49)
%The first two inputs must have the same number of elements.
%Error in SolarAppGG/JobSectorsInSolarDropDownValueChanged (line 57)
%IPDcoef= polyfit(app.xyears,app.ymanu,1);
%Error in %matlab.apps.AppBase>@(source,event)executeCallback(ams,app,callback,requiresEventData,ev%ent) (line 62)
% newCallback = @(source, event)executeCallback(ams, ...
%Error while evaluating DropDown PrivateValueChangedFcn.

Accepted Answer

dpb
dpb on 16 Oct 2024
Moved: dpb on 16 Oct 2024
We can't see variables app.xyears,app.yipd, but if you set a breakpoint at that line, you'll be able to look at them and you'll find they are not the same length for some reason. Why, we can't tell, but that's the problem.
Example:
c=polyfit([1:3],[1:3],1) % two row vectors same length works
c = 1×2
1.0000 0.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
c=polyfit([1:3],[1:3].',1) % two vectors same length works despite orientation different
c = 1×2
1.0000 0.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
c=polyfit([1:4],[1:3],1) % two vectors different length crashes and burns...
Error using polyfit (line 49)
The first two inputs must have the same number of elements.
Figure out why you have the two different lengths at that point and fix it...
  2 Comments
dpb
dpb on 17 Oct 2024
" i just merged years and ipd into one..."
Well, that doesn't seem right if
plot(app.UIAxes,app.xyears,app.yipd,'ob')
is right--that implies somewhat like the variable names do, btw--that xyears is a time variable and yipd is some dependent variable. Although it should have failed also if the two lengths aren't the same...
>> plot(1:3,rand(1,4),1)
Error using plot
Vectors must be the same length.
>>
And, it won't work in polyfit without an x and a y vector...and clearly using the same for both is, while it will run, pretty-much useless since it would be fitting x on x for the same two x.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!