[英]Loopless function calls on vector/matrix members in Matlab/Octave
I came into matrix world from loop world (C, etc) 我从循环世界(C等)进入矩阵世界
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. 现在,关于MATLAB / Octave的所有建议都说:只要你发现自己使用循环并想出更好的方法,就停止。
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. 也许,它只是语法糖,这就是全部,但仍然有用。
In matlab the '.' 在matlab中'。' prefix on operators is element-wise operation. 运算符上的前缀是元素操作。
Try something like this: 尝试这样的事情:
function r = newfun(v)
r = a.*exp(-(v-b).^2./(2*c^2))
end
The function should look like this: 该函数应如下所示:
function retval = gauss(v, a, b, c)
retval = a*exp(-(v-b).^2/(2*c^2));
I would recommend you to read MATLAB documentation on how to vectorize the code and avoid loops: 我建议你阅读关于如何矢量化代码和避免循环的MATLAB文档:
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. 还要记住,有时使用循环的代码可以更清晰地进行向量化,而最近引入的JIT编译器MATLAB可以很好地处理循环。
Yes. 是。
function retval = newfun(v)
retval = a*exp(-((v-b).^2)/(2*c*c));
endfunction
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.