如何通过更改函数语句在Matlab中输出表?

时间:2019-03-23 23:26:14

标签: matlab output

我用表中“列”变量制作向量的技术仅在部分时间内有效。以下代码中的K1与index有何不同?我正在调试数值方法,并且需要列索引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".

1 个答案:

答案 0 :(得分:0)

您正在清除变量,然后才能返回它们。您收到的错误可以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,了解函数如何与工作空间一起使用。