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

前端 未结 4 1624
走了就别回头了
走了就别回头了 2021-01-18 23:08

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/matri

相关标签:
4条回答
  • 2021-01-18 23:26

    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.

    0 讨论(0)
  • 2021-01-18 23:26

    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
    
    0 讨论(0)
  • 2021-01-18 23:29

    Yes.

    function retval = newfun(v)
        retval = a*exp(-((v-b).^2)/(2*c*c));
    endfunction
    
    0 讨论(0)
  • 2021-01-18 23:53

    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.

    0 讨论(0)
提交回复
热议问题