2017-07-14 46 views
0

我知道,我知道在這個論壇和其他論壇上已經有幾個類似的問題。我閱讀並嘗試了所有...雖然沒有爲我工作。如何在MATLAB中通過特定的點來限制擬合曲線,同時實現梯度

我跟着this MATLAB後解決我的問題,這裏的代碼

x0 = Xh(end,1); %end point of previous curve to add on 
y0 = fh(end,1); %end point of previous curve to add on 

x = A.data(co2:end,1); %a 17280 x 1 double of real data (shaky) 
y = A.data(co2:end,31); %a 17280 x 1 double of real data (shaky) 
% 'C' is the Vandermonde matrix for 'x' 
n = 25; % Degree of polynomial to fit 
V(:,n+1) = ones(length(x),1,class(x)); 
for j = n:-1:1 
    V(:,j) = x.*V(:,j+1); 
end 
C = V; 
% 'd' is the vector of target values, 'y'. 
d = y; 
%% 
% There are no inequality constraints in this case, i.e., 
A = []; 
b = []; 
%% 
% We use linear equality constraints to force the curve to hit the required point. In 
% this case, 'Aeq' is the Vandermoonde matrix for 'x0' 
Aeq = x0.^(n:-1:0); 
% and 'beq' is the value the curve should take at that point 
beq = y0; 
%% 
p = lsqlin(C, d, A, b, Aeq, beq) 
%% 
% We can then use POLYVAL to evaluate the fitted curve 
yhat = polyval(p, x); 
%% 
% Plot original data 
plot(x,y,'.b-') 
hold on 
% Plot point to go through 
plot(x0,y0,'gx','linewidth',4) 
% Plot fitted data 
plot(x,yhat,'g','linewidth',2) 
hold off 

此代碼的工作非常適合我的擬合曲線,並迫使它要經過我的出發點而言。但就平滑地將曲線添加到前一曲線而言,起點應該具有與之前曲線相同的曲線。它也應該以固定的漸變結束。

所以我需要的實現是:


添加更多然後一個固定點([X0,Y0],[X1,Y1],...)

集梯度在固定X0,X1,...

我知道polyfix這樣做過,但在這個擬合過程代碼在我的情況下不起作用。 lsqlin的結果要好得多。這仍然是我正在尋找的東西。

你能幫我編輯上面的代碼來添加這些功能嗎?

+0

編號「gimme teh codez」的問題在堆棧溢出問題之外。當你有一個特定的問題或錯誤時,自己添加這些功能並回來。 – dasdingonesin

回答

1

你應該增加更多的約束方程來優化問題,FE:

Aeq(1, :) = x0.^(n:-1:0); 
beq(1, :) = x0; 
Aeq(2, :) = x1.^(n:-1:0); 
beq(2, :) = y1; 
Aeq(3, 1:end-1) = x0.^(n-1:-1:0) .* (n:-1:1); 
beq(3, :) = dy0; 
Aeq(4, 1:end-1) = x1.^(n-1:-1:0) .* (n:-1:1); 
beq(4, :) = dy1; 

爲了得到一階導數約束方程,這是一個好主意,通過先用手試試吧一個小多項式訂購。

下輸入:

p_exact = [1 2 3 4 5 6]; 
x0 = 0; 
y0 = 0; 
dy0 = 0; 
x1 = 1; 
y1 = 10; 
dy1 = 100; 

x = (0:0.001:1)'; 
y = polyval(p_exact, x)+randn(size(x)); 
n = 7; % Degree of polynomial to fit 

生成的輸出:

enter image description here

您清楚地看到你的擬合曲線上的約束效應,即比較紅色和綠色的曲線。