简体   繁体   English

错误:'x' 未定义

[英]Error : 'x' undefined

I got a problem with running Octave function (ODE), I've tried already present solutions for this problem but nothing is working.我在运行 Octave 函数 (ODE) 时遇到问题,我已经尝试过针对此问题提供的解决方案,但没有任何效果。 I've also tried by saving my filename as egzamin.m but it too not worked.我也试过将我的文件名保存为egzamin.m但它也不起作用。

Code from octave :八度代码:

function dx=egzamin(x,t)
dx=zeros(4,1);
b=0;
g=9.81;
x1=x(1);
y1=x(2);
Vx=x(3);
Vy=x(4);
dx(1)=Vx;
dx(2)=Vy;
dx(3)=-b*Vx*sqrt(Vx.^2+Vy.^2);
dx(4)=-b*Vy*sqrt(Vx.^2+Vy.^2)-g;
endfunction
N=mod(291813,100);
x1=0;
y1=0;
Vx=20+N;
Vy=20+N;

t=0:0.01:500;
sol=lsode("egzamin",[x1,y1,Vx,Vy],t);
plot(sol(:,1),sol(:,2)) 

The error is :错误是:

error: 'x' undefined near line 5 column 4
error: called from
    egzamin at line 5 column 3

Since the file starts with function , it is not a script file, as explained in the doc :由于文件以function开头,因此它不是脚本文件,如文档中所述:

Unlike a function file, a script file must not begin with the keyword function与函数文件不同,脚本文件不能以关键字 function 开头

Add any statement (even dummy like 1; ) before the function line to get a script file.function行之前添加任何语句(甚至像1;这样的虚拟语句)以获取脚本文件。

# dummy statement to get a script file instead of a function file   
1;

function dx=egzamin(x,t)
  g = 9.81;
  Vx = x(3);
  Vy = x(4);
  dx = [Vx, Vy, 0, -g];
endfunction

N=mod(291813,100);
x1=0;
y1=0;
Vx=20+N;
Vy=20+N;

t=0:0.01:500;
sol=lsode("egzamin",[x1,y1,Vx,Vy],t);
plot(sol(:,1),sol(:,2))

A very clear explanation of what's going on is given here .这里给出对正在发生的事情的非常清楚的解释。

You need to save the function (thus from function to endfunction and naught else) as egzamin.m , and then execute the rest of the code in a script or at the command line.您需要将函数(因此从function保存到endfunction而不是其他function )为egzamin.m ,然后在脚本中或在命令行中执行其余代码。 Alternatively, provided Octave does that the same as what MATLAB does nowadays, first put your script ( N=(..) to plot() ) and then the function.或者,如果 Octave 与现在的 MATLAB 所做的相同,首先将您的脚本( N=(..)plot() )然后是函数。

This is necessary since you are defining your function first, so it doesn't have any inputs yet, as you don't define them until later.这是必要的,因为您首先要定义函数,因此它还没有任何输入,因为您要稍后才定义它们。 The function needs to have its inputs defined before it executes, hence you need to save your function separately.该函数需要执行之前定义其输入,因此您需要单独保存您的函数。

You can of course save your "script" bit, thus everything which is currently below your function declaration, as a function as well, simply don't give it in- and outputs, or, set all the input parameters here as well.您当然可以保存您的“脚本”位,因此当前在您的函数声明之下的所有内容,作为一个函数,只是不要给它输入和输出,或者也在这里设置所有输入参数。 (Which I wouldn't do as it's the same as your egzamin then.) eg (我不会这样做,因为它和你的egzamin一样。)例如

function []=MyFunc()
N=mod(291813,100);
x1=0;
y1=0;
Vx=20+N;
Vy=20+N;

t=0:0.01:500;
sol=lsode("egzamin",[x1,y1,Vx,Vy],t);
plot(sol(:,1),sol(:,2)) 
endfunction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM