Matlab/Octave 中向量/矩阵成员的无循环函数调用
我从循环世界(C 等)进入矩阵世界,
我想在向量/矩阵的每个单独成员上调用一个函数,并返回结果向量/矩阵。
这就是我目前的做法:
function retval = gauss(v, a, b, c)
for i = 1:length(v)
retval(i) = a*(e^(-(v(i)-b)*(v(i)-b)/(2*c*c)));
endfor
endfunction
示例用法:
octave:47> d=[1:1000];
octave:48> mycurve=gauss(d, 1, 500, 100);
现在,关于 MATLAB/Octave 的所有建议都说:每当您发现自己使用循环时,请停止并思考更好的方法。
因此,我的问题是:可以在向量/矩阵的每个成员上调用函数并在不使用显式循环的情况下一次性返回新向量/矩阵中的结果吗?
那就是我正在寻找一些东西像这样:
function retval = newfun(v)
retval = 42*(v^23);
endfunction
也许,这只是语法糖,仅此而已,但了解一下仍然很有用。
I came into matrix world from loop world (C, etc)
I would like to call a function on each individual member of a vector/matrix, and return the resulting vector/matrix.
This is how I currently do it:
function retval = gauss(v, a, b, c)
for i = 1:length(v)
retval(i) = a*(e^(-(v(i)-b)*(v(i)-b)/(2*c*c)));
endfor
endfunction
Example usage:
octave:47> d=[1:1000];
octave:48> mycurve=gauss(d, 1, 500, 100);
Now, all advice on MATLAB/Octave says: STOP whenever you catch yourself using loops and think of a better way of doing it.
Thus, my question: Can one call a function on each member of a vector/matrix and return the result in a new vector/matrix all at once without using explicit loops?
That is I am looking for something like this:
function retval = newfun(v)
retval = 42*(v^23);
endfunction
Perhaps, it is just syntactic sugar, that is all, but still would be useful to know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该函数应如下所示:
我建议您阅读有关如何向量化代码并避免循环的 MATLAB 文档:
代码矢量化指南
提高性能的技术
另请记住,有时带有循环的代码比矢量化代码更清晰,并且随着最近引入的 JIT 编译器,MATLAB 可以很好地处理循环。
The function should look like this:
I would recommend you to read MATLAB documentation on how to vectorize the code and avoid loops:
Code Vectorization Guide
Techniques for Improving Performance
Also remember that sometime code with loops can be more clear that vectorized one, and with recent introduction of JIT compiler MATLAB deals with loops pretty well.
在 Matlab 中,“.”运算符的前缀是按元素操作。
尝试这样的事情:
In matlab the '.' prefix on operators is element-wise operation.
Try something like this:
ARRAYFUN (及其亲属)是通常的方式这样做。
但在你的特殊情况下,你可以这样做
这不仅仅是语法糖;消除循环可以使代码运行得更快。
ARRAYFUN (and its relatives) is the usual way to do that.
But in your particular case, you can just do
It's not just syntactic sugar; eliminating loops makes your code run substantially faster.
是的。
Yes.