2014-11-20 152 views
0
霍納功能

我有以下的家庭作業問題:麻煩與MATLAB

Apply linear least squares with the two models S1(A, B, C) = Ax^2 + Bx + C and S2(A, B, C, D) = Ax^3 + Bx^2 + Cx + D to the data set (0, 4), (1, −1), (2, 6), (3, 1), (4, −4), (5, −9). Solve in MATLAB using lspoly. Report the values of the parameters A, B, C and D clearly, and produce a plot showing the data and both fitting curves.

我用下面的函數在MATLAB工作:

功能1

function y = horner(a,c) 

n=length(a)-1; 
y=a(n+1); 

for k = n:-1:1 
    y = a(k)+ c*y; 
end 

功能2

function C = lspoly(x,y,M) 

n = length(x); 
F = zeros(n,M+1); 
for k = 1:M+1 
    F(:,k) = x'.^(k-1); 
end 
A = F'*F; 
B = F'*y'; 
C = A\B; 

這是我寫的問題代碼:

clc 
clear all 
close all 

x = [0, 1, 2, 3, 4, 5]; 
y = [4, -1, 6, 1, -4, -9]; 

C = lspoly(x,y,2); % finds the parameters 
xx = 0:0.01:5; 
yy = zeros(1, length(xx)); 
for i=1:length(xx) 
    yy(i) = horner(C,xx(i)); 
end 

CC = lspoly(x,y,3); % finds the parameters 
xxx = 0:0.1:5; 
yyy = zeros(1, length(xxx)); 
for i=1:length(xxx) 
    yyy(i) = horner(CC,xxx(i)); 
end 

figure(1) 
plot(x, y, 'o', xx, yy, 'r-', xxx, yyy, 'b-') 

我遇到與此代碼的一些問題。當我嘗試運行該程序,我得到以下錯誤:

In an assignment A(I) = B, the number of elements in B and I must be the same.

Error in HW7_1 (line 14) yy(i) = horner(C,xx(i));

我真的不能換我的頭周圍究竟是什麼我需要做什麼來解決這個問題。我試着一塊一塊地分解我的程序,以確定代碼中不同位置的結果,但至今沒有發現任何注意事項。

有人可以幫我解決這個錯誤嗎?

+0

它在Octave 3.8中對我很好。我唯一能想到的是在MATLAB中有一個名爲'horner'的內置函數(符號數學工具箱的一部分),所以也許你的代碼正在調用那個函數而不是你的函數。也許嘗試將其重命名爲'my_horner'或類似的東西。 – am304 2014-11-20 17:06:08

+0

哇,就是這樣。謝謝!所有這些令人頭疼的問題,這樣一個簡單的錯誤哈哈 – xcdemon05 2014-11-20 17:45:28

+0

不用擔心,我會把它作爲答案,你可以接受它。 – am304 2014-11-20 17:58:25

回答

0

它在Octave 3.8中對我很好。我唯一能想到的是在MATLAB中有一個名爲horner的內置函數(Symbolic Math Toolbox的一部分),所以也許你的代碼正在調用那個函數而不是你的函數。也許嘗試將其重命名爲不同的東西,如my_horner或類似的。