我的 Octave 函数有什么问题?
我只是尝试在八度音阶中创建我的第一个函数,它看起来如下:
function hui(x)
if(0 <= x && x <2)
retval = (1.5 * x + 2)
elseif(2<= x && x <4)
retval = (-x + 5)
elseif(4<= x && x < 6)
retval = (0.5 * x)
elseif(6<= x && x < 8)
retval = (x - 3)
elseif(8<= x && x <=10)
retval = (2 * x - 11)
endif
endfunction
但如果我尝试使用以下命令绘制它: x=0:0.1:10; plot(x, hui(x));
它显示了一个情节女巫似乎有点奇怪。
我做错了什么?
提前致谢 约翰
I just tried to create my first function in octave, it looks as follows:
function hui(x)
if(0 <= x && x <2)
retval = (1.5 * x + 2)
elseif(2<= x && x <4)
retval = (-x + 5)
elseif(4<= x && x < 6)
retval = (0.5 * x)
elseif(6<= x && x < 8)
retval = (x - 3)
elseif(8<= x && x <=10)
retval = (2 * x - 11)
endif
endfunction
but if I try to plot it using: x=0:0.1:10; plot(x, hui(x));
It shows a plot witch seems a little bit strange.
What did I wrong?
Thanks in advance
John
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须原谅我对软件包的生疏,但您需要稍微更改一下代码。值得注意的是,符号
0<=x
是不正确的,必须是x>=0
。由于 hui 是在向量上操作的,我相信您在构造返回值时需要考虑到这一点。我确信有更有效的方法对此进行矢量化,但基本上,在跳过输入向量时,我将最新值添加到返回向量上,最后删除我输入的初始 0。我把在哨兵值中,以防输入不满足其中一个条件(它始终采用代码中的“else”路径,因此在那里放置某些内容可能会提醒您出现错误)。
You'll have to pardon my rustiness with the package, but you need to change the code around a bit. Notably, the notation
0<=x
is incorrect, and must bex>=0
. Sincehui
is operating on a vector, I believe you need to take that into account when constructing your return value.I'm sure there are more effective ways of vectorizing this, but basically, While stepping over the input vector, I added the latest value onto the return vector, and at the end lopping off the initial 0 that I had put in. I put in a sentinel value in case the input didn't fulfill one of the criteria (it was always taking the "else" path in your code, so putting something there could have alerted you to something being wrong).
x
是一个向量,因此您要么需要循环遍历它,要么对代码进行向量化以消除这种需要。当您使用 Octave 时,值得对所有可能的内容进行矢量化。我能想到的最简单的方法是:
y(x >= a & x < b)
语法是逻辑索引。单独来说,x >= a & x < b
为您提供一个逻辑值向量,但与另一个向量结合,您可以获得满足条件的值。 Octave 还可以让你做这样的作业。x
is a vector, so you either need to loop through it or vectorise your code to removing the need.As you're using Octave, it's worth vectorising everything you possibly can. The easiest way I can think of doing this is:
The
y(x >= a & x < b)
syntax is logical indexing. Alone,x >= a & x < b
gives you a vector of logical values, but combined with another vector you get the values which meet the condition. Octave will also let you do assignments like this.