我從表中的“列”變數創建向量的技術僅在部分時間有效。 K1 與下面程式碼中的索引有什麼不同?我正在調試數值方法,我需要列索引 X、K1、K2、K、Y。
功能代碼:
function [index,X,K1,K2,K,Y] = impeulerT(x,y,x1,n)
% modified version of Improved Euler method found in
% Elementary Differential Equations by Edwards and Penney
X=x; % initial x
Y=y; % initial y
x1 = x1; % final x
n = n; % number of subintervals
h = (x1-x)/n; % step size
index = 0; % initialize index
k1=0;
k2=0;
k=0;
for i=1:n; % begin loop
k1=f(x,y); % first slope
k2=f(x+h,y+h*k1); % second slope
k=(k1+k2)/2; % average slope
x=x+h; % new x
y=y+h*k; % new y
X=[X;x]; % update x-column
Y=[Y;y]; % update y-column
index = [index;i]; % update index-column
K1=[K1;k1]; Line 22
K2=[K2;k2];
K= [K;k];
end % end loop
ImprovedEulerTable=table(index,X,K1,K2,K,Y)
end
呼叫代碼:
[index,X,K1,K2,K,Y] = impeulerT(0,1,1,10);
紀錄:
>> [index,X,K1,K2,K,Y] = impeulerT(0,1,1,10);
Undefined function or variable 'K1'.
Error in impeulerT (line 22)
K1=[K1;k1];
22 K1=[K1;k1];
>>
答案1
這段程式碼比較好。可以更改輸出的第一行以更好地匹配手動完成的操作。基本上這意味著 K1、K2 和 K 列可以向上移動一行。其他列可以保持不變。然而,這與愛德華茲和彭尼相匹配。請注意此處 K1、K2 和 K 的定義方式。乾杯!毫米
功能代碼:
function [index,X,Y,K1,K2,K] = impeulerT(x,y,x1,n)
% modified version of Improved Euler method found in
% Elementary Differential Equations by Edwards and Penney
X=x; % initial x
Y=y; % initial y
x1 = x1; % final x
n = n; % number of subintervals
h = (x1-x)/n; % step size
index = 0; % initialize index
% Initialize the lower-case variables
k1=0;
k2=0;
k=0;
% Initialize the upper-case variables
K1=k1;
K2=k2;
K =k;
for i=1:n; % begin loop
k1=f(x,y); % first slope
k2=f(x+h,y+h*k1); % second slope
k=(k1+k2)/2; % average slope
x=x+h; % new x
y=y+h*k; % new y
X=[X;x]; % update x-column
Y=[Y;y]; % update y-column
index = [index;i]; % update index-column
K1=[K1;k1]; % update K1 column
K2=[K2;k2]; % update K2 column
K= [K;k]; % update K column
end % end loop
ImprovedEulerTable=table(index,X,Y,K1,K2,K)
end
呼叫代碼:
% Improved Euler
[index,X,Y,K1,K2,K] = impeulerTX(0,1,1,10);
答案2
錯誤在於第 22 行方K1=[K1;k1];
括號內有 K1,但之前沒有定義。
K1=[];
解決辦法是在for迴圈之前定義。
編輯:所有其他變數也是如此。所以這段程式碼有效
function [index,X,K1,K2,K,Y] = impeulerT(x,y,x1,n)
% modified version of Improved Euler method found in
% Elementary Differential Equations by Edwards and Penney
X=x; % initial x
Y=y; % initial y
x1 = x1; % final x
n = n; % number of subintervals
h = (x1-x)/n; % step size
index = 0; % initialize index
k1=0;
k2=0;
k=0;
% Initialize the upper-case variables
K1=[];
K2=[];
K=[];
for i=1:n; % begin loop
k1=f(x,y); % first slope
k2=f(x+h,y+h*k1); % second slope
k=(k1+k2)/2; % average slope
x=x+h; % new x
y=y+h*k; % new y
X=[X;x]; % update x-column
Y=[Y;y]; % update y-column
index = [index;i]; % update index-column
K1=[K1;k1]; % Line 22
K2=[K2;k2];
K= [K;k];
end % end loop
ImprovedEulerTable=table(index,X,K1,K2,K,Y)
end