Problem with Linear Regression

Hi, everyone. I have a problem with Linear Regression. My code is :
knobSetting = [0 1 2 3 4 5]';
flowRate = [0.0 2.3 4.2 7.2 8.4 11.9]' ;
flowfit=fit(knobSetting,flowRate,'poly1');
Matlab gives me the following problem :
'fit' requires one of the following:
- Curve Fitting Toolbox
-Predictive Maintenance Toolbox
Error in Untitled2 (line 3)
flowfit=fit(knobSetting,flowRate,'poly1')

Answers (4)

Stephan
Stephan on 25 Feb 2019
Edited: Stephan on 25 Feb 2019
Hi,
this problem can be solved easily by using mldivide. No additional toolboxes are needed:
knobSetting = [0 1 2 3 4 5]';
flowRate = [0.0 2.3 4.2 7.2 8.4 11.9]';
flowfit = knobSetting\flowRate
flowrate_calc = flowfit .* knobSetting
scatter(knobSetting,flowRate,'*r')
hold on
plot(knobSetting,flowrate_calc)
hold off
The result is a least squares fit of your data, where flowfit represents the slope of the linear function. Since your function goes through (0,0) this is the most simple case.
Best regards
Stephan
A first-degree polynomial is a linear fit. You do not need any toolboxes to do a linear fit.
Try this:
knobSetting = [0 1 2 3 4 5]';
flowRate = [0.0 2.3 4.2 7.2 8.4 11.9]';
B = [knobSetting, ones(size(knobSetting))] \ flowRate;
regfit = [knobSetting, ones(size(knobSetting))] *B;
figure
plot(knobSetting, flowRate, 'p')
hold on
plot(knobSetting, regfit,' -r')
hold off
grid
text(0.6, 9, sprintf('flowRate = %.3f\\cdotknobSetting%.3f', B))
You can simply use the built-in polyfit(x, y, 1) to get the equation of a line fitting your data, then use polyval() to get the fitted y-values at whatever x-locations you want:
% Create and plot existing data.
knobSetting = [0 1 2 3 4 5]';
flowRate = [0.0 2.3 4.2 7.2 8.4 11.9]' ;
coefficients = polyfit(knobSetting, flowRate, 1); % Get coefficients of the line.
plot(knobSetting, flowRate, 'bo');
hold on;
% Now get fitted values at the same Knob settings locations and plot them.
fittedValues = polyval(coefficients, knobSetting);
plot(knobSetting, fittedValues, 'r*-', 'MarkerSize', 10);
grid on;
legend('Actual', 'Fitted', 'Location', 'north');
0000 Screenshot.png
Claudia Orlando
Claudia Orlando on 11 Mar 2019
Thank you all for your valuable advice.

Categories

Asked:

on 25 Feb 2019

Answered:

on 11 Mar 2019

Community Treasure Hunt

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

Start Hunting!