Map function in MATLAB?

前端 未结 7 842
情书的邮戳
情书的邮戳 2020-11-29 17:11

I\'m a little surprised that MATLAB doesn\'t have a Map function, so I hacked one together myself since it\'s something I can\'t live without. Is there a better version out

7条回答
  •  孤城傲影
    2020-11-29 18:16

    If matlab does not have a built in map function, it could be because of efficiency considerations. In your implementation you are using a loop to iterate over the elements of the list, which is generally frowned upon in the matlab world. Most built-in matlab functions are "vectorized", i. e. it is more efficient to call a function on an entire array, than to iterate over it yourself and call the function for each element.

    In other words, this

    
    a = 1:10;
    a.^2
    

    is much faster than this

    
    a = 1:10;
    map(@(x)x^2, a)
    

    assuming your definition of map.

提交回复
热议问题