Reputation: 5945
I am trying to figure out a way to do the following without a loop:
Lets say I have a vector x
where I sum some elements e
into. I also have a vector of indices ids
which say to which elements of x
to send the values to. i.e.
x = zeros(1,4);
e = [ 1 10 100 1e3 1e4];
ids = [1 1 2 4 3];
I would like to do something like
x(ids) = x(ids) + e
That will return
x =
11 100 10000 1000
because we refer to x(1) twice, while instead it returns
x =
10 100 10000 1000
Upvotes: 0
Views: 105
Reputation: 1797
accumaray
is a really useful function for doing such tricks. In your case:
accumarray(ids',e)
will do the job.
Upvotes: 3