How do I perform a piecewise linear approximation on nonlinear data?

I need to perform the linear approximation for every hour of every day in 2017. Here the Electricity Price and volume data is for 1 hour in a day
xdata = [-500:3000]; %Price data in Euros (not regularly distributed)
ydata = [27370:67599]; %Volume data in MWh (every xdata point has 1 corresponding y data point)
n=382;
% Create axes
axes1 = axes;
hold(axes1,'on');
% Create plot
plot(xdata,ydata);
box(axes1,'on');
%Least Squares Curve fit
%Simple linear model (ydata = theta(1)*xdata + theta(2))
fun = @(theta, xdata) theta(1) + ...
(xdata<=theta(2)) .* theta(3) .* xdata + ...
(xdata>theta(2)) .* (theta(3) * theta(2) + ...
theta(4) .* (xdata-theta(2)));
%Fit model using starting point x0=[xdata(1), ydata(1)]
x0 = [xdata(1), ydata(1)];
theta = lsqcurvefit(fun, x0, xdata, ydata);
%Data and fitted curve plot
times = linspace(xdata(1),xdata(end));
plot(xdata,ydata, 'bo', times, fun(theta, times),'r-')
legend('Observed Data','Fitted curve')
title('13 April 2017')
Error shown in command window: Index exceeds matrix dimensions.
Error in (theta,xdata)theta(1)+(xdata<=theta(2)).*theta(3).*xdata+(xdata>theta(2)).*(theta(3)*theta(2)+theta(4).*(xdata-theta(2)))
Error in lsqcurvefit (line 202) initVals.F = feval(funfcn_x_xdata{3},xCurrent,XDATA,varargin{:});
Caused by: Failure in initial objective function evaluation. LSQCURVEFIT cannot continue.
I am not sure if the free-knot BBspline approximation is applicable because with huge data I am using I would want the knots to change according to the data. Would you suggest an alternative?

回答 (0 件)

カテゴリ

質問済み:

2018 年 5 月 27 日

編集済み:

2018 年 5 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by