Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition through linear indexing

I have a 256 x 256 matrix M, and have produced some linear indexes L.

Also I have a vector of weights, of numels same as L, to be added to the elements of M indexed by L. Problem is, with the expression

M(L) = M(L) + weights;

For duplicate values in L, only the last corresponding element in weights will be added.

Is there a simple way to resolve this/am I missing something?

like image 218
Temp Avatar asked Dec 11 '25 01:12

Temp


1 Answers

I think the way to go here is using accumarray:

% The 'data'
M = zeros(10,5); % Suppose this is your matrix
L = [46 47 47 46 48 49 48 48 48]'; % The linear index numbers
weights = [4 7 4 6 4 9 48 8 48]'; % The weights for these index numbers

% Make sure the indices are in ascending order
Y = SORTROWS([L weights]);

% Determining the weights to be added
idx = unique(Y(:,1));
weights_unique = accumarray(Y(:,1),Y(:,2));

% The addition
M(idx) = M(idx) + weights_unique(weights_unique>0);
like image 111
Dennis Jaheruddin Avatar answered Dec 12 '25 18:12

Dennis Jaheruddin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!