Loopless function calls on vector/matrix members in Matlab/Octave

若如初见. 提交于 2019-12-01 17:42:59

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:

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.

In matlab the '.' 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

ARRAYFUN (and its relatives) is the usual way to do that.

But in your particular case, you can just do

mycurve = a*exp(-(d-b).^2/(2*c^2));

It's not just syntactic sugar; eliminating loops makes your code run substantially faster.

Yes.

function retval = newfun(v)
    retval = a*exp(-((v-b).^2)/(2*c*c));
endfunction
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!