1

I want to sum the elements of the matrix M according to the the values in the matrix R into the array d.

Theoretically, it's cannot be serialized, because the action of summing into one array (D) requires memory access to the same data.

I implemented it in the following way

for ind = 1: numel(R)
    d(R(ind)) = d(R(ind)) + M(ind);      
end 

like @Andrew suggested in this related topic: How do I iterate through each element in an n-dimensional matrix in MATLAB?

The elements of the array R and not every large, but also not 1 or 2, it can be for example 1 to 15.

Is there a more efficient way to do it in Matlab, even if the "theoretical complexity" of the action would be worse ?

For it could be solved also by iterating over the possible values in R and summing the elements of M in indexes where R = val , or anything more "built-in" in Matlab, which don't "like" loops generally speaking.

In SQL for example you have a "built-in" method to collapse repetition of one column and get the sum of the values in the other column.

There is a topic about similar action but in different langauge : Collapse a matrix to sum values in one column by values in another

Community
  • 1
  • 1
ip84
  • 190
  • 1
  • 1
  • 9

2 Answers2

2

It is probable that this can be done using Matlab's accumarray function. Something like this:

d = accumarray(R, M, expected_size_of_d)

But it would be useful if you give us example values for M and R and the expected d, since the exact solution might depend on the shape of your matrices, the fact if you use linear indexing or not ...

Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62
0

Your question is not very clear. If you want to sum selected elements of M, where the selection is given by R, you can do as follows:

dsum(M(sub2ind(size(M),R(:,1),R(:,2))))

For example, consider

M = [1 2 3;
     4 5 6;
     7 8 9];

R = [1 1; 3 1; 2 2]; % each row selects an element of M

The result gives M(1,1) + M(3,1) + M(2,2):

>> sum(M(sub2ind(size(M),R(:,1),R(:,2))))
ans =
    13
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147