What is the fastest way to perform arithmetic operations on each element of a cell array?

前端 未结 1 919
深忆病人
深忆病人 2020-12-09 23:03

Say I want to multiply each element of a cell array A with a coefficent k. I can do that by:

<         


        
1条回答
  •  有刺的猬
    2020-12-09 23:36

    Not exactly an answer, but here is a way to see the affect of JIT compiler and accelerator in both approaches (cellfun vs. for-loop):

    feature('jit', 'off'); feature('accel', 'off');
    tic, A = cellfun(@(x) k*x, A, 'UniformOutput', false); toc
    tic, for i=1:numel(A), A{i} = A{i}*k; end, toc
    
    feature('jit', 'on'); feature('accel', 'on');
    tic, A = cellfun(@(x) k*x, A, 'UniformOutput', false); toc
    tic, for i=1:numel(A), A{i} = A{i}*k; end, toc
    

    I get the following

    Elapsed time is 25.913995 seconds.
    Elapsed time is 13.050288 seconds.
    

    vs.

    Elapsed time is 10.053347 seconds.
    Elapsed time is 1.978974 seconds.
    

    with optimization turned on in the second.

    By the way, parallel parfor performed much worse (at least on my local test machine with a pool size of 2 processes).

    Seeing the results you posted, MEX-function is the way to go :)

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