我在表格中使用“列”变量制作向量的技术仅在部分时间内有效。以下代码中的索引与K1有什么不同?我正在调试一个数值方法,我需要列索引,X,K1,K2,K,Y。一切正常,直到我添加K1,K2和K?怎么做?
MM
需要的是适当地初始化K1,k1,K2,k2,K和k。更正后的代码如下。
功能代码:
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; K1=k1; % initialize k1
k2=0; K2=k2; % initialize k2
k=0; K=k; % initialize 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,K1,K2,K,Y)
clear
end
电话代码:
[index,X,K1,K2,K,Y] = impeulerT(0,1,1,10);
日志:
Output argument "index" (and maybe others) not
assigned during call to "impeulerT".
您正在清除变量,然后才能返回它们。您收到的错误可以解释为here。
要修复代码,只需在创建表后删除或注释clear语句:
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; K1=k1; % initialize k1
k2=0; K2=k2; % initialize k2
k=0; K=k; % initialize k
for i=1:n; % begin loop
k1=(x/y); % first slope
k2=(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,K1,K2,K,Y);
end
通常,您不必担心清除已调用函数内的变量,因为这些变量只保留在该函数的工作空间内。唯一改变的变量是返回的变量。阅读更多关于函数如何使用工作空间的here。