1

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.

Community
  • 1
  • 1

1 Answers1

1

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Thank you! Works perfectly fine. Now i just have find a way to do this in c++. Armadillo doesnt support sparse initialization using identical indices. So may be i will have to look for some other library. – Nishant Kapoor Nov 01 '16 at 05:08
  • I was wrong. Armadillo does support sparse matrix initialization using identical locations `sp_mat(add_values, locations, values, n_rows, n_cols, sort_locations = true, check_for_zeros = true)`. Thank you for your answer. – Nishant Kapoor Nov 01 '16 at 12:31