清除所有变量后,用户创建的 Matlab 函数将失败
User Made Matlab Function Fails Once All Variables are Cleared
昨天我最初问this question,自己找到了答案;然而,我在 Matlab 中使用了 clear all
命令,现在函数抛出错误 Undefined function or variable 'y'
。
我使用了答案中的代码
函数 [s1] = L_Analytic3(eqn,t0,h,numstep,y0)
%Differential Equation solver for specific inputs
% eqn is the differential equation
% t0 is start of evaluation interval
% h is stepize
% numstep is the number of steps
% y0 is the initial condition
syms y(x)
cond = y(0) == y0;
A = dsolve(eqn, cond);
s1 = A;
S1 = s1;
for x = t0 : h : h*(numstep)
subs(x);
if x == t0
S1 = subs(s1,x);
else
S1 = [subs(S1), subs(s1,vpa(x))];
end
end
end
并在输入clear all
后将L_Analytic3(diff(y) == y,0,0.1,5,1)
放入命令Window中。我必须 运行 一个单独的代码
syms y(x)
cond = y(0) == 1;
A = dsolve(diff(y) == y, cond);
在使用我的函数之前,为了让函数工作。这仅仅是因为 A
、ans
、cond
、x
和 y
在使用函数之前已经由 3 行代码定义了吗?如果是这样,有没有一种方法可以让我不必先使用那 3 行代码就可以使用该功能?
当您执行 L_Analytic3(diff(y) == ...);
时,您没有定义变量 y,因此 MATLAB 会抱怨 - 它无法知道 y
是将在您调用的函数中定义的符号。您不需要全部 3 行代码。 syms y(x)
应该足以定义 y 并让您使用所需的函数调用。
现在,我看到有 2 种简单的方法可以解决此问题:
- 具有
syms y(x)
的脚本(或其他函数),然后按照您的方式调用 L_Analytic3
(现在不需要 syms y(x)
,它具有已经定义了)。
- 改用匿名方程式作为输入,比如
@(x) diff(x)==x
,并将 L_Analytic3
的一行稍微更改为 A = dsolve(eqn(y), cond);
这两种方法都适用,不知道第二种方法是否会在更复杂的情况下中断。如果你正在做符号的东西,我可能会选择第一个版本,如果你想对数字和符号函数进行相同的函数调用,我可能会选择第二个版本。
昨天我最初问this question,自己找到了答案;然而,我在 Matlab 中使用了 clear all
命令,现在函数抛出错误 Undefined function or variable 'y'
。
我使用了答案中的代码
函数 [s1] = L_Analytic3(eqn,t0,h,numstep,y0)
%Differential Equation solver for specific inputs
% eqn is the differential equation
% t0 is start of evaluation interval
% h is stepize
% numstep is the number of steps
% y0 is the initial condition
syms y(x)
cond = y(0) == y0;
A = dsolve(eqn, cond);
s1 = A;
S1 = s1;
for x = t0 : h : h*(numstep)
subs(x);
if x == t0
S1 = subs(s1,x);
else
S1 = [subs(S1), subs(s1,vpa(x))];
end
end
end
并在输入clear all
后将L_Analytic3(diff(y) == y,0,0.1,5,1)
放入命令Window中。我必须 运行 一个单独的代码
syms y(x)
cond = y(0) == 1;
A = dsolve(diff(y) == y, cond);
在使用我的函数之前,为了让函数工作。这仅仅是因为 A
、ans
、cond
、x
和 y
在使用函数之前已经由 3 行代码定义了吗?如果是这样,有没有一种方法可以让我不必先使用那 3 行代码就可以使用该功能?
当您执行 L_Analytic3(diff(y) == ...);
时,您没有定义变量 y,因此 MATLAB 会抱怨 - 它无法知道 y
是将在您调用的函数中定义的符号。您不需要全部 3 行代码。 syms y(x)
应该足以定义 y 并让您使用所需的函数调用。
现在,我看到有 2 种简单的方法可以解决此问题:
- 具有
syms y(x)
的脚本(或其他函数),然后按照您的方式调用L_Analytic3
(现在不需要syms y(x)
,它具有已经定义了)。 - 改用匿名方程式作为输入,比如
@(x) diff(x)==x
,并将L_Analytic3
的一行稍微更改为A = dsolve(eqn(y), cond);
这两种方法都适用,不知道第二种方法是否会在更复杂的情况下中断。如果你正在做符号的东西,我可能会选择第一个版本,如果你想对数字和符号函数进行相同的函数调用,我可能会选择第二个版本。