question about vectorization using indexes
1 view (last 30 days)
Show older comments
Commented: Andrei Bobrov on 31 Jul 2019
Hello, I am trying to do the following operations in matlab but I have a problem with how to properly write my code using vectorization. This is just an example, m, n and the values of the vectors and matrices are just to illustrate my problem. In reality m and n can go up to 1000.
I tried the following but it does not give correct results.
Thank you in advance
Stephen23 on 30 Jul 2019
Edited: Stephen23 on 30 Jul 2019
Note that ind and b must be transposed for this to work:
>> a = [4;2;1;3;1;4;4;0]; % must be column!
>> ind = [1,0;2,3;4,0;3,3;5,3].'; % transposed!
>> b = [5,0;2,2;1,0;2,2;2,2].'; % transposed!
>> idx = b~=0;
>> XC = ind(idx);
>> bC = b(idx);
>> [~,idc] = find(idx);
>> out = accumarray(idc,a(XC).^bC,,@prod)
More Answers (2)
Guillaume on 30 Jul 2019
Edited: Guillaume on 30 Jul 2019
Another option is to append a 0 (or any finite value) to the start of a and increase ind by 1, so a(ind+1) is always valid. Assuming that b is 0 when ind is 0 as in your example (if not, it's trivially fixed), then anything.^0 is 1 and multiplying by 1 doesn't affect the result, so:
apadded = [0; a];
c = prod(apadded(ind + 1) .^ b, 2)
As a bonus, c is a column vector matching the rows of b.
If b can be non-zero when ind is 0:
c = prod(apadded(ind + 1) . ^ (b .* (ind ~= 0)), 2)
edit: actually, if b can be non-zero when ind is 0, the easiest is to pad a with a 1 instead of a zero. Since 1.^anything is 1, it doesn't affect anything:
apadded = [1; a];
c = prod(apadded(ind + 1) .^b, 2) %b can be zero or non-zero where ind is 0. It'll result in 1.^something
Guillaume on 31 Jul 2019
Note: although both options are very fast even for very large inputs, this option is about twice as fast as the accepted answer. And much simpler and using less memory.
ind(ind == 0) = 1;
c = prod(a(ind).^b,2);
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!