Reputation: 125
I have a vector J which contains the row index of a vector.
I would like to do the following code in a vectorized way : I want to sum the duplicate values to the variable 'Mode' from the variable 'M'. I have size(M)=size(J)
. This is my attempted code:
Mode=zeros(n,1);
for i=1:length(J)
Mode(J(i))=Mode(J(i))+M(i);
end
I have tested with
Mode(J)=M
but the problem is that there are some duplicate index value in J. How can I implement it correctly ?
Upvotes: 1
Views: 79
Reputation: 14939
You're probably looking for accumarray
.
Have a look at this example:
J = [1 2 3 5 2 3].';
M = [1 1 1 1 1 1].';
Mode = accumarray(J, M, size(J))
Mode =
1
2
2
0
1
0
From the documentation:
A = accumarray(subs,val)
returns arrayA
by accumulating elements of vectorval
using the subscriptssubs
. Ifsubs
is a column vector, then each element defines a corresponding subscript in the output, which is also a column vector. Theaccumarray
function collects all elements ofval
that have identical subscripts insubs
and stores their sum in the location ofA
corresponding to that subscript (for index i, A(i)=sum(val(subs(:)==i)))
. Elements ofA
whose subscripts do not appear insubs
are equal to0
.
size(J)
is used to make sure the dimension of Mode
is the same as the dimension of J
.
According to OP, the following code works:
A=accumarray(J,M);
Mode(1:size(A))=A;
Upvotes: 3