1

I have a for loop performing the current operation:

T = [1,1,1,4,5,6,3];
A = [20,15,4,21,14,3];
l = length(T);

% how can we vectorize this?
for(i = 1:l)
    A(T(i)) = A(T(i)) + 1;
end

Simply put, it uses the T vector as a list of indices to increment on the A array in a particular order. For instance, the first element in array A will be incremented 3 times (corresponding to the 3 ones in T), while the rest get incremented once, 2 doesn't get incremented. The resulting changes to A are thus:

A = [23,15,5,22,15,4];

However, ideally I would like to avoid a for loop here. Before I tried:

A(T) = A(T) + 1;

This didn't work; MATLAB just ignores the repeated indices. Is there someway I can perform the operation in the for loop by vectorisation or some other means?

2 Answers 2

3

With accumarray:

T = [1,1,1,4,5,6,3];
A = [20,15,4,21,14,3];
res = A + accumarray(T(:), 1, [numel(A) 1]).';
Sign up to request clarification or add additional context in comments.

2 Comments

A + accumarray(T(:), 1, [numel(A) 1])' otherwise Matlab complains: When SUBS is a column vector, the third input SZ must be of the form [N 1].
Also s = accumarray(T(:),1).'; w = 1:numel(s); A(w) = A(w)+s;
0
[q,w] = hist(T,0:numel(A));
A(w(q>0)) = A(w(q>0)) + q(q>0);


A =

23    15     5    22    15     4

Explanation:

You can use hist to know how many time each index occurs in T. Since indexes are integers, you can specify the ranges from 0 to the number of elements of A.

Hist will then return two vectors:

q is the number of occurrences of each index:

q =

0     3     0     1     1     1     1     0     0     0     0

w are the indexes themselves:

w =

0     1     2     3     4     5     6     7     8     9    10

Then you just take the indexes that occur at least once w(q>0) as the indexes of A to be updated, and you update those indexes by the number of occurrences q(q>0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.