How to write vectorized functions in MATLAB

后端 未结 4 1025
时光取名叫无心
时光取名叫无心 2021-02-09 16:41

I am just learning MATLAB and I find it hard to understand the performance factors of loops vs vectorized functions.

In my previous question: Nested for

4条回答
  •  时光取名叫无心
    2021-02-09 17:34

    In this case

    M = median(A,dim) returns the median values for elements along the dimension of A specified by scalar dim
    

    But with a general function you can try splitting your array with mat2cell (which can work with n-D arrays and not just matrices) and applying your my_median_1D function through cellfun. Below I will use median as an example to show that you get equivalent results, but instead you can pass it any function defined in an m-file, or an anonymous function defined with the @(args) notation.

    >> testarr = [[1 2 3]' [4 5 6]']
    
    testarr =
    
         1     4
         2     5
         3     6
    
    >> median(testarr,2)
    
    ans =
    
        2.5000
        3.5000
        4.5000
    
    >> shape = size(testarr)
    
    shape =
    
         3     2
    
    >> cellfun(@median,mat2cell(testarr,repmat(1,1,shape(1)),[shape(2)]))
    
    ans =
    
        2.5000
        3.5000
        4.5000
    

提交回复
热议问题