repmat vs simple matrix multiplication in MATLAB

前端 未结 2 1832
陌清茗
陌清茗 2021-01-25 02:00

Let v be a row vector of length n. The goal is to create a matrix A with m rows that are all equal to v.

MATLAB has a function for this that is

相关标签:
2条回答
  • 2021-01-25 02:04

    Lets compare them!

    When testing algorithms 2 metrics are important: time, and memory.

    Lets start with time:

    Clearly repmat wins!

    Memory:

    profile -memory on
    for m=1000:1000:50000
    f1=@()(repmat(v,[m 1]));
    f2=@()(ones(m,1)*v);
    ii=ii+1;
    t1(ii)=timeit(f1);
    t2(ii)=timeit(f2);
    end
    profreport
    

    It seems that both take the same amount of memory. However, the profiler is known for not showing all the memory, so we can not fully trust it.

    Still, it is clear that repmat is better

    0 讨论(0)
  • 2021-01-25 02:13

    You should use repmat().

    Matrix Multiplication is O(n ^ 3) operation which is much slower then replicating data in memory.
    On top of that, the second option allocate more data in memory of the size of the output.

    In the case above you create a vector which the outer multiplication is faster yet still not as memory operation.

    MATLAB doesn't use the knowledge all vector elements are 1, hence you multiply each element of x by 1 m times.

    Both operations will be mainly memory bounded, yet more efficient, fast and direct method would be going with repmat().

    The question is, what you do afterwards?
    Because you may not need repmat().

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