Cellfun versus Simple Matlab Loop performance

后端 未结 4 1601
挽巷
挽巷 2020-11-27 19:41

When I started working with matlab sometime ago in the university, my supervisor would kill me if he saw any unnecessary for loop (he would ask for exchanging it for k

4条回答
  •  天涯浪人
    2020-11-27 20:27

    clear all;
    ntimes = 1000;
    
    r = 100;
    c = 100;
    d = 100;
    A = rand(r, c, d);
    B = rand(r, c, d);
    
    tic
    for i = 1:ntimes
        for j = 1 : d
            result = A(:, :, j) * B(:, :, j);
        end
    end
    toc
    
    A_cell = num2cell(A, [1 2]);
    B_cell = num2cell(B, [1 2]);
    tic
    for i = 1 : ntimes
        result2 = cellfun(@(x, y) x*y, A_cell, B_cell, 'uni', 0);
    end
    toc
    

    Try this maybe. Test it for few more times. On average, cellfun is faster than the double loop.

提交回复
热议问题