开发者

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

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 开发者_如何学JAVAam 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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜