Search code examples
matlabsparse-matrixaccumarray

Matlab's Accumarray using Sparse matrix multiplication


I have the following instruction in matlab

out = accumarray (A,B,sz);

where B and A is of size 1x957600 and 957600x1 respectively and sz is [1445 1]. The result out is of 1445x1 size.

My question is how can we implement this instruction without using accumarray and using sparse matrix multiplication.

I found this following solution but i dont know how to implement it according to the data i have

Matlab Code

%fake data setup
    M=1e5;
    A=kron(speye(M),ones(1,16));
    N=size(A,2);
    [I,J]=find(A);
    x=rand(N,1);
    %pretend we build A from scratch
    tic; 
     A=sparse(I,J,1);
    toc %Elapsed time is 0.062737 seconds.
    %Apply A
    tic
      y1=A*x;
    toc %Elapsed time is 0.006868 seconds.
    %Using accumarray
    b=x(J);
    tic
     y2=accumarray(I,b,[M,1]);
    toc %Elapsed time is 0.012236 seconds.

I am asking this question because i want to use accumarray in c++. I have a solution for that but its taking a lot of time to do the computation. Here is my question from two days ago which has the c++ implementation for accumarray.


Solution

  • Use

    sparse(A, 1, B, sz(1), sz(2))
    

    Example:

    A = [5;4;6;5;2;5;2;5;5;2];
    B = [6 3 1 4 9 8 1 5 8 9];
    sz = [10 1];
    out = accumarray (A,B,sz);
    out2 = sparse(A, 1, B, sz(1), sz(2));
    

    This gives

    >> out
    out =
         0
        19
         0
         3
        31
         1
         0
         0
         0
         0
    >> full(out2)
    ans =
         0
        19
         0
         3
        31
         1
         0
         0
         0
         0