Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: Increment of matrix values with indices

I have a vector of indices and want to increase values in matrix in every index. For example:

    ind = [1 2 2 5];
    m = zeros(3);
    m(ind) = m(ind) + 1;

The result is as follow:

    m = [1 0 0
         1 1 0
         0 0 0]

But I need the results to be

    m = [1 0 0
         2 1 0
         0 0 0]

The time complexity is very important to me, and I can't use for. Thanks.

like image 411
user137927 Avatar asked Dec 11 '22 10:12

user137927


1 Answers

Here's a way. I haven't timed it.

ind = [1 2 2 5];
N = 3;
m = full(reshape(sparse(ind, 1, 1, N^2, 1), N, N));

Equivalently, you can use

ind = [1 2 2 5];
N = 3;
m = reshape(accumarray(ind(:), 1, [N^2 1]), N, N);

or its variation (thanks to @beaker)

ind = [1 2 2 5];
N = 3;
m = zeros(N);
m(:) = accumarray(ind(:), 1, [N^2 1]);

This one is probably slower than the others:

ind = [1 2 2 5];
N = 3;
m = zeros(N);
[ii, ~, vv] = find(accumarray(ind(:), 1));
m(ii) = vv;
like image 141
Luis Mendo Avatar answered Dec 27 '22 20:12

Luis Mendo